Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaOverload.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
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 provides Sema routines for C++ overloading.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/CXXInheritance.h"
15
#include "clang/AST/DeclObjC.h"
16
#include "clang/AST/DependenceFlags.h"
17
#include "clang/AST/Expr.h"
18
#include "clang/AST/ExprCXX.h"
19
#include "clang/AST/ExprObjC.h"
20
#include "clang/AST/TypeOrdering.h"
21
#include "clang/Basic/Diagnostic.h"
22
#include "clang/Basic/DiagnosticOptions.h"
23
#include "clang/Basic/PartialDiagnostic.h"
24
#include "clang/Basic/SourceManager.h"
25
#include "clang/Basic/TargetInfo.h"
26
#include "clang/Sema/Initialization.h"
27
#include "clang/Sema/Lookup.h"
28
#include "clang/Sema/Overload.h"
29
#include "clang/Sema/SemaInternal.h"
30
#include "clang/Sema/Template.h"
31
#include "clang/Sema/TemplateDeduction.h"
32
#include "llvm/ADT/DenseSet.h"
33
#include "llvm/ADT/Optional.h"
34
#include "llvm/ADT/STLExtras.h"
35
#include "llvm/ADT/SmallPtrSet.h"
36
#include "llvm/ADT/SmallString.h"
37
#include <algorithm>
38
#include <cstdlib>
39
40
using namespace clang;
41
using namespace sema;
42
43
using AllowedExplicit = Sema::AllowedExplicit;
44
45
692k
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46
1.12M
  return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47
1.12M
    return P->hasAttr<PassObjectSizeAttr>();
48
1.12M
  });
49
692k
}
50
51
/// A convenience routine for creating a decayed reference to a function.
52
static ExprResult
53
CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54
                      const Expr *Base, bool HadMultipleCandidates,
55
                      SourceLocation Loc = SourceLocation(),
56
103k
                      const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57
103k
  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58
6
    return ExprError();
59
  // If FoundDecl is different from Fn (such as if one is a template
60
  // and the other a specialization), make sure DiagnoseUseOfDecl is
61
  // called on both.
62
  // FIXME: This would be more comprehensively addressed by modifying
63
  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64
  // being used.
65
103k
  if (FoundDecl != Fn && 
S.DiagnoseUseOfDecl(Fn, Loc)11.6k
)
66
6
    return ExprError();
67
103k
  DeclRefExpr *DRE = new (S.Context)
68
103k
      DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
69
103k
  if (HadMultipleCandidates)
70
52.1k
    DRE->setHadMultipleCandidates(true);
71
72
103k
  S.MarkDeclRefReferenced(DRE, Base);
73
103k
  if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74
103k
    if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75
6.25k
      S.ResolveExceptionSpec(Loc, FPT);
76
6.25k
      DRE->setType(Fn->getType());
77
6.25k
    }
78
103k
  }
79
103k
  return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80
103k
                             CK_FunctionToPointerDecay);
81
103k
}
82
83
static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84
                                 bool InOverloadResolution,
85
                                 StandardConversionSequence &SCS,
86
                                 bool CStyle,
87
                                 bool AllowObjCWritebackConversion);
88
89
static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90
                                                 QualType &ToType,
91
                                                 bool InOverloadResolution,
92
                                                 StandardConversionSequence &SCS,
93
                                                 bool CStyle);
94
static OverloadingResult
95
IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96
                        UserDefinedConversionSequence& User,
97
                        OverloadCandidateSet& Conversions,
98
                        AllowedExplicit AllowExplicit,
99
                        bool AllowObjCConversionOnExplicit);
100
101
static ImplicitConversionSequence::CompareKind
102
CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103
                                   const StandardConversionSequence& SCS1,
104
                                   const StandardConversionSequence& SCS2);
105
106
static ImplicitConversionSequence::CompareKind
107
CompareQualificationConversions(Sema &S,
108
                                const StandardConversionSequence& SCS1,
109
                                const StandardConversionSequence& SCS2);
110
111
static ImplicitConversionSequence::CompareKind
112
CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113
                                const StandardConversionSequence& SCS1,
114
                                const StandardConversionSequence& SCS2);
115
116
/// GetConversionRank - Retrieve the implicit conversion rank
117
/// corresponding to the given implicit conversion kind.
118
29.7M
ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119
29.7M
  static const ImplicitConversionRank
120
29.7M
    Rank[(int)ICK_Num_Conversion_Kinds] = {
121
29.7M
    ICR_Exact_Match,
122
29.7M
    ICR_Exact_Match,
123
29.7M
    ICR_Exact_Match,
124
29.7M
    ICR_Exact_Match,
125
29.7M
    ICR_Exact_Match,
126
29.7M
    ICR_Exact_Match,
127
29.7M
    ICR_Promotion,
128
29.7M
    ICR_Promotion,
129
29.7M
    ICR_Promotion,
130
29.7M
    ICR_Conversion,
131
29.7M
    ICR_Conversion,
132
29.7M
    ICR_Conversion,
133
29.7M
    ICR_Conversion,
134
29.7M
    ICR_Conversion,
135
29.7M
    ICR_Conversion,
136
29.7M
    ICR_Conversion,
137
29.7M
    ICR_Conversion,
138
29.7M
    ICR_Conversion,
139
29.7M
    ICR_Conversion,
140
29.7M
    ICR_Conversion,
141
29.7M
    ICR_OCL_Scalar_Widening,
142
29.7M
    ICR_Complex_Real_Conversion,
143
29.7M
    ICR_Conversion,
144
29.7M
    ICR_Conversion,
145
29.7M
    ICR_Writeback_Conversion,
146
29.7M
    ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
147
                     // it was omitted by the patch that added
148
                     // ICK_Zero_Event_Conversion
149
29.7M
    ICR_C_Conversion,
150
29.7M
    ICR_C_Conversion_Extension
151
29.7M
  };
152
29.7M
  return Rank[(int)Kind];
153
29.7M
}
154
155
/// GetImplicitConversionName - Return the name of this kind of
156
/// implicit conversion.
157
0
static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158
0
  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159
0
    "No conversion",
160
0
    "Lvalue-to-rvalue",
161
0
    "Array-to-pointer",
162
0
    "Function-to-pointer",
163
0
    "Function pointer conversion",
164
0
    "Qualification",
165
0
    "Integral promotion",
166
0
    "Floating point promotion",
167
0
    "Complex promotion",
168
0
    "Integral conversion",
169
0
    "Floating conversion",
170
0
    "Complex conversion",
171
0
    "Floating-integral conversion",
172
0
    "Pointer conversion",
173
0
    "Pointer-to-member conversion",
174
0
    "Boolean conversion",
175
0
    "Compatible-types conversion",
176
0
    "Derived-to-base conversion",
177
0
    "Vector conversion",
178
0
    "SVE Vector conversion",
179
0
    "Vector splat",
180
0
    "Complex-real conversion",
181
0
    "Block Pointer conversion",
182
0
    "Transparent Union Conversion",
183
0
    "Writeback conversion",
184
0
    "OpenCL Zero Event Conversion",
185
0
    "C specific type conversion",
186
0
    "Incompatible pointer conversion"
187
0
  };
188
0
  return Name[Kind];
189
0
}
190
191
/// StandardConversionSequence - Set the standard conversion
192
/// sequence to the identity conversion.
193
82.0M
void StandardConversionSequence::setAsIdentityConversion() {
194
82.0M
  First = ICK_Identity;
195
82.0M
  Second = ICK_Identity;
196
82.0M
  Third = ICK_Identity;
197
82.0M
  DeprecatedStringLiteralToCharPtr = false;
198
82.0M
  QualificationIncludesObjCLifetime = false;
199
82.0M
  ReferenceBinding = false;
200
82.0M
  DirectBinding = false;
201
82.0M
  IsLvalueReference = true;
202
82.0M
  BindsToFunctionLvalue = false;
203
82.0M
  BindsToRvalue = false;
204
82.0M
  BindsImplicitObjectArgumentWithoutRefQualifier = false;
205
82.0M
  ObjCLifetimeConversionBinding = false;
206
82.0M
  CopyConstructor = nullptr;
207
82.0M
}
208
209
/// getRank - Retrieve the rank of this standard conversion sequence
210
/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
211
/// implicit conversions.
212
7.88M
ImplicitConversionRank StandardConversionSequence::getRank() const {
213
7.88M
  ImplicitConversionRank Rank = ICR_Exact_Match;
214
7.88M
  if  (GetConversionRank(First) > Rank)
215
0
    Rank = GetConversionRank(First);
216
7.88M
  if  (GetConversionRank(Second) > Rank)
217
6.08M
    Rank = GetConversionRank(Second);
218
7.88M
  if  (GetConversionRank(Third) > Rank)
219
0
    Rank = GetConversionRank(Third);
220
7.88M
  return Rank;
221
7.88M
}
222
223
/// isPointerConversionToBool - Determines whether this conversion is
224
/// a conversion of a pointer or pointer-to-member to bool. This is
225
/// used as part of the ranking of standard conversion sequences
226
/// (C++ 13.3.3.2p4).
227
3.51M
bool StandardConversionSequence::isPointerConversionToBool() const {
228
  // Note that FromType has not necessarily been transformed by the
229
  // array-to-pointer or function-to-pointer implicit conversions, so
230
  // check for their presence as well as checking whether FromType is
231
  // a pointer.
232
3.51M
  if (getToType(1)->isBooleanType() &&
233
3.51M
      
(5.96k
getFromType()->isPointerType()5.96k
||
234
5.96k
       
getFromType()->isMemberPointerType()5.94k
||
235
5.96k
       
getFromType()->isObjCObjectPointerType()5.92k
||
236
5.96k
       
getFromType()->isBlockPointerType()5.91k
||
237
5.96k
       
First == ICK_Array_To_Pointer5.91k
||
First == ICK_Function_To_Pointer5.74k
))
238
217
    return true;
239
240
3.51M
  return false;
241
3.51M
}
242
243
/// isPointerConversionToVoidPointer - Determines whether this
244
/// conversion is a conversion of a pointer to a void pointer. This is
245
/// used as part of the ranking of standard conversion sequences (C++
246
/// 13.3.3.2p4).
247
bool
248
StandardConversionSequence::
249
3.51M
isPointerConversionToVoidPointer(ASTContext& Context) const {
250
3.51M
  QualType FromType = getFromType();
251
3.51M
  QualType ToType = getToType(1);
252
253
  // Note that FromType has not necessarily been transformed by the
254
  // array-to-pointer implicit conversion, so check for its presence
255
  // and redo the conversion to get a pointer.
256
3.51M
  if (First == ICK_Array_To_Pointer)
257
1.34k
    FromType = Context.getArrayDecayedType(FromType);
258
259
3.51M
  if (Second == ICK_Pointer_Conversion && 
FromType->isAnyPointerType()2.42k
)
260
652
    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
261
580
      return ToPtrType->getPointeeType()->isVoidType();
262
263
3.51M
  return false;
264
3.51M
}
265
266
/// Skip any implicit casts which could be either part of a narrowing conversion
267
/// or after one in an implicit conversion.
268
static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
269
192k
                                             const Expr *Converted) {
270
  // We can have cleanups wrapping the converted expression; these need to be
271
  // preserved so that destructors run if necessary.
272
192k
  if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
273
7
    Expr *Inner =
274
7
        const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
275
7
    return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
276
7
                                    EWC->getObjects());
277
7
  }
278
279
385k
  
while (auto *192k
ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280
192k
    switch (ICE->getCastKind()) {
281
0
    case CK_NoOp:
282
188k
    case CK_IntegralCast:
283
189k
    case CK_IntegralToBoolean:
284
191k
    case CK_IntegralToFloating:
285
191k
    case CK_BooleanToSignedIntegral:
286
191k
    case CK_FloatingToIntegral:
287
191k
    case CK_FloatingToBoolean:
288
192k
    case CK_FloatingCast:
289
192k
      Converted = ICE->getSubExpr();
290
192k
      continue;
291
292
251
    default:
293
251
      return Converted;
294
192k
    }
295
192k
  }
296
297
192k
  return Converted;
298
192k
}
299
300
/// Check if this standard conversion sequence represents a narrowing
301
/// conversion, according to C++11 [dcl.init.list]p7.
302
///
303
/// \param Ctx  The AST context.
304
/// \param Converted  The result of applying this standard conversion sequence.
305
/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
306
///        value of the expression prior to the narrowing conversion.
307
/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
308
///        type of the expression prior to the narrowing conversion.
309
/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
310
///        from floating point types to integral types should be ignored.
311
NarrowingKind StandardConversionSequence::getNarrowingKind(
312
    ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
313
2.60M
    QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
314
2.60M
  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
315
316
  // C++11 [dcl.init.list]p7:
317
  //   A narrowing conversion is an implicit conversion ...
318
0
  QualType FromType = getToType(0);
319
2.60M
  QualType ToType = getToType(1);
320
321
  // A conversion to an enumeration type is narrowing if the conversion to
322
  // the underlying type is narrowing. This only arises for expressions of
323
  // the form 'Enum{init}'.
324
2.60M
  if (auto *ET = ToType->getAs<EnumType>())
325
2.96k
    ToType = ET->getDecl()->getIntegerType();
326
327
2.60M
  switch (Second) {
328
  // 'bool' is an integral type; dispatch to the right place to handle it.
329
266
  case ICK_Boolean_Conversion:
330
266
    if (FromType->isRealFloatingType())
331
2
      goto FloatingIntegralConversion;
332
264
    if (FromType->isIntegralOrUnscopedEnumerationType())
333
259
      goto IntegralConversion;
334
    // -- from a pointer type or pointer-to-member type to bool, or
335
5
    return NK_Type_Narrowing;
336
337
  // -- from a floating-point type to an integer type, or
338
  //
339
  // -- from an integer type or unscoped enumeration type to a floating-point
340
  //    type, except where the source is a constant expression and the actual
341
  //    value after conversion will fit into the target type and will produce
342
  //    the original value when converted back to the original type, or
343
2.12k
  case ICK_Floating_Integral:
344
2.13k
  FloatingIntegralConversion:
345
2.13k
    if (FromType->isRealFloatingType() && 
ToType->isIntegralType(Ctx)107
) {
346
107
      return NK_Type_Narrowing;
347
2.02k
    } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
348
2.02k
               ToType->isRealFloatingType()) {
349
2.02k
      if (IgnoreFloatToIntegralConversion)
350
12
        return NK_Not_Narrowing;
351
2.01k
      const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
352
2.01k
      assert(Initializer && "Unknown conversion expression");
353
354
      // If it's value-dependent, we can't tell whether it's narrowing.
355
2.01k
      if (Initializer->isValueDependent())
356
0
        return NK_Dependent_Narrowing;
357
358
2.01k
      if (Optional<llvm::APSInt> IntConstantValue =
359
2.01k
              Initializer->getIntegerConstantExpr(Ctx)) {
360
        // Convert the integer to the floating type.
361
1.93k
        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
362
1.93k
        Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
363
1.93k
                                llvm::APFloat::rmNearestTiesToEven);
364
        // And back.
365
1.93k
        llvm::APSInt ConvertedValue = *IntConstantValue;
366
1.93k
        bool ignored;
367
1.93k
        Result.convertToInteger(ConvertedValue,
368
1.93k
                                llvm::APFloat::rmTowardZero, &ignored);
369
        // If the resulting value is different, this was a narrowing conversion.
370
1.93k
        if (*IntConstantValue != ConvertedValue) {
371
7
          ConstantValue = APValue(*IntConstantValue);
372
7
          ConstantType = Initializer->getType();
373
7
          return NK_Constant_Narrowing;
374
7
        }
375
1.93k
      } else {
376
        // Variables are always narrowings.
377
79
        return NK_Variable_Narrowing;
378
79
      }
379
2.01k
    }
380
1.92k
    return NK_Not_Narrowing;
381
382
  // -- from long double to double or float, or from double to float, except
383
  //    where the source is a constant expression and the actual value after
384
  //    conversion is within the range of values that can be represented (even
385
  //    if it cannot be represented exactly), or
386
1.71k
  case ICK_Floating_Conversion:
387
1.71k
    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
388
1.71k
        Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
389
      // FromType is larger than ToType.
390
1.70k
      const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391
392
      // If it's value-dependent, we can't tell whether it's narrowing.
393
1.70k
      if (Initializer->isValueDependent())
394
0
        return NK_Dependent_Narrowing;
395
396
1.70k
      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
397
        // Constant!
398
1.66k
        assert(ConstantValue.isFloat());
399
0
        llvm::APFloat FloatVal = ConstantValue.getFloat();
400
        // Convert the source value into the target type.
401
1.66k
        bool ignored;
402
1.66k
        llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
403
1.66k
          Ctx.getFloatTypeSemantics(ToType),
404
1.66k
          llvm::APFloat::rmNearestTiesToEven, &ignored);
405
        // If there was no overflow, the source value is within the range of
406
        // values that can be represented.
407
1.66k
        if (ConvertStatus & llvm::APFloat::opOverflow) {
408
13
          ConstantType = Initializer->getType();
409
13
          return NK_Constant_Narrowing;
410
13
        }
411
1.66k
      } else {
412
40
        return NK_Variable_Narrowing;
413
40
      }
414
1.70k
    }
415
1.66k
    return NK_Not_Narrowing;
416
417
  // -- from an integer type or unscoped enumeration type to an integer type
418
  //    that cannot represent all the values of the original type, except where
419
  //    the source is a constant expression and the actual value after
420
  //    conversion will fit into the target type and will produce the original
421
  //    value when converted back to the original type.
422
237k
  case ICK_Integral_Conversion:
423
237k
  IntegralConversion: {
424
237k
    assert(FromType->isIntegralOrUnscopedEnumerationType());
425
0
    assert(ToType->isIntegralOrUnscopedEnumerationType());
426
0
    const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427
237k
    const unsigned FromWidth = Ctx.getIntWidth(FromType);
428
237k
    const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429
237k
    const unsigned ToWidth = Ctx.getIntWidth(ToType);
430
431
237k
    if (FromWidth > ToWidth ||
432
237k
        
(205k
FromWidth == ToWidth205k
&&
FromSigned != ToSigned89.2k
) ||
433
237k
        
(133k
FromSigned133k
&&
!ToSigned130k
)) {
434
      // Not all values of FromType can be represented in ToType.
435
189k
      const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436
437
      // If it's value-dependent, we can't tell whether it's narrowing.
438
189k
      if (Initializer->isValueDependent())
439
1.12k
        return NK_Dependent_Narrowing;
440
441
187k
      Optional<llvm::APSInt> OptInitializerValue;
442
187k
      if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443
        // Such conversions on variables are always narrowing.
444
3.86k
        return NK_Variable_Narrowing;
445
3.86k
      }
446
184k
      llvm::APSInt &InitializerValue = *OptInitializerValue;
447
184k
      bool Narrowing = false;
448
184k
      if (FromWidth < ToWidth) {
449
        // Negative -> unsigned is narrowing. Otherwise, more bits is never
450
        // narrowing.
451
84.3k
        if (InitializerValue.isSigned() && InitializerValue.isNegative())
452
9
          Narrowing = true;
453
99.6k
      } else {
454
        // Add a bit to the InitializerValue so we don't have to worry about
455
        // signed vs. unsigned comparisons.
456
99.6k
        InitializerValue = InitializerValue.extend(
457
99.6k
          InitializerValue.getBitWidth() + 1);
458
        // Convert the initializer to and from the target width and signed-ness.
459
99.6k
        llvm::APSInt ConvertedValue = InitializerValue;
460
99.6k
        ConvertedValue = ConvertedValue.trunc(ToWidth);
461
99.6k
        ConvertedValue.setIsSigned(ToSigned);
462
99.6k
        ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463
99.6k
        ConvertedValue.setIsSigned(InitializerValue.isSigned());
464
        // If the result is different, this was a narrowing conversion.
465
99.6k
        if (ConvertedValue != InitializerValue)
466
118
          Narrowing = true;
467
99.6k
      }
468
184k
      if (Narrowing) {
469
127
        ConstantType = Initializer->getType();
470
127
        ConstantValue = APValue(InitializerValue);
471
127
        return NK_Constant_Narrowing;
472
127
      }
473
184k
    }
474
232k
    return NK_Not_Narrowing;
475
237k
  }
476
477
2.36M
  default:
478
    // Other kinds of conversions are not narrowings.
479
2.36M
    return NK_Not_Narrowing;
480
2.60M
  }
481
2.60M
}
482
483
/// dump - Print this standard conversion sequence to standard
484
/// error. Useful for debugging overloading issues.
485
0
LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
486
0
  raw_ostream &OS = llvm::errs();
487
0
  bool PrintedSomething = false;
488
0
  if (First != ICK_Identity) {
489
0
    OS << GetImplicitConversionName(First);
490
0
    PrintedSomething = true;
491
0
  }
492
493
0
  if (Second != ICK_Identity) {
494
0
    if (PrintedSomething) {
495
0
      OS << " -> ";
496
0
    }
497
0
    OS << GetImplicitConversionName(Second);
498
499
0
    if (CopyConstructor) {
500
0
      OS << " (by copy constructor)";
501
0
    } else if (DirectBinding) {
502
0
      OS << " (direct reference binding)";
503
0
    } else if (ReferenceBinding) {
504
0
      OS << " (reference binding)";
505
0
    }
506
0
    PrintedSomething = true;
507
0
  }
508
509
0
  if (Third != ICK_Identity) {
510
0
    if (PrintedSomething) {
511
0
      OS << " -> ";
512
0
    }
513
0
    OS << GetImplicitConversionName(Third);
514
0
    PrintedSomething = true;
515
0
  }
516
517
0
  if (!PrintedSomething) {
518
0
    OS << "No conversions required";
519
0
  }
520
0
}
521
522
/// dump - Print this user-defined conversion sequence to standard
523
/// error. Useful for debugging overloading issues.
524
0
void UserDefinedConversionSequence::dump() const {
525
0
  raw_ostream &OS = llvm::errs();
526
0
  if (Before.First || Before.Second || Before.Third) {
527
0
    Before.dump();
528
0
    OS << " -> ";
529
0
  }
530
0
  if (ConversionFunction)
531
0
    OS << '\'' << *ConversionFunction << '\'';
532
0
  else
533
0
    OS << "aggregate initialization";
534
0
  if (After.First || After.Second || After.Third) {
535
0
    OS << " -> ";
536
0
    After.dump();
537
0
  }
538
0
}
539
540
/// dump - Print this implicit conversion sequence to standard
541
/// error. Useful for debugging overloading issues.
542
0
void ImplicitConversionSequence::dump() const {
543
0
  raw_ostream &OS = llvm::errs();
544
0
  if (hasInitializerListContainerType())
545
0
    OS << "Worst list element conversion: ";
546
0
  switch (ConversionKind) {
547
0
  case StandardConversion:
548
0
    OS << "Standard conversion: ";
549
0
    Standard.dump();
550
0
    break;
551
0
  case UserDefinedConversion:
552
0
    OS << "User-defined conversion: ";
553
0
    UserDefined.dump();
554
0
    break;
555
0
  case EllipsisConversion:
556
0
    OS << "Ellipsis conversion";
557
0
    break;
558
0
  case AmbiguousConversion:
559
0
    OS << "Ambiguous conversion";
560
0
    break;
561
0
  case BadConversion:
562
0
    OS << "Bad conversion";
563
0
    break;
564
0
  }
565
566
0
  OS << "\n";
567
0
}
568
569
7.98k
void AmbiguousConversionSequence::construct() {
570
7.98k
  new (&conversions()) ConversionSet();
571
7.98k
}
572
573
15.9k
void AmbiguousConversionSequence::destruct() {
574
15.9k
  conversions().~ConversionSet();
575
15.9k
}
576
577
void
578
8.00k
AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579
8.00k
  FromTypePtr = O.FromTypePtr;
580
8.00k
  ToTypePtr = O.ToTypePtr;
581
8.00k
  new (&conversions()) ConversionSet(O.conversions());
582
8.00k
}
583
584
namespace {
585
  // Structure used by DeductionFailureInfo to store
586
  // template argument information.
587
  struct DFIArguments {
588
    TemplateArgument FirstArg;
589
    TemplateArgument SecondArg;
590
  };
591
  // Structure used by DeductionFailureInfo to store
592
  // template parameter and template argument information.
593
  struct DFIParamWithArguments : DFIArguments {
594
    TemplateParameter Param;
595
  };
596
  // Structure used by DeductionFailureInfo to store template argument
597
  // information and the index of the problematic call argument.
598
  struct DFIDeducedMismatchArgs : DFIArguments {
599
    TemplateArgumentList *TemplateArgs;
600
    unsigned CallArgIndex;
601
  };
602
  // Structure used by DeductionFailureInfo to store information about
603
  // unsatisfied constraints.
604
  struct CNSInfo {
605
    TemplateArgumentList *TemplateArgs;
606
    ConstraintSatisfaction Satisfaction;
607
  };
608
}
609
610
/// Convert from Sema's representation of template deduction information
611
/// to the form used in overload-candidate information.
612
DeductionFailureInfo
613
clang::MakeDeductionFailureInfo(ASTContext &Context,
614
                                Sema::TemplateDeductionResult TDK,
615
1.37M
                                TemplateDeductionInfo &Info) {
616
1.37M
  DeductionFailureInfo Result;
617
1.37M
  Result.Result = static_cast<unsigned>(TDK);
618
1.37M
  Result.HasDiagnostic = false;
619
1.37M
  switch (TDK) {
620
16
  case Sema::TDK_Invalid:
621
2.26k
  case Sema::TDK_InstantiationDepth:
622
34.5k
  case Sema::TDK_TooManyArguments:
623
183k
  case Sema::TDK_TooFewArguments:
624
195k
  case Sema::TDK_MiscellaneousDeductionFailure:
625
195k
  case Sema::TDK_CUDATargetMismatch:
626
195k
    Result.Data = nullptr;
627
195k
    break;
628
629
12.8k
  case Sema::TDK_Incomplete:
630
14.4k
  case Sema::TDK_InvalidExplicitArguments:
631
14.4k
    Result.Data = Info.Param.getOpaqueValue();
632
14.4k
    break;
633
634
998
  case Sema::TDK_DeducedMismatch:
635
999
  case Sema::TDK_DeducedMismatchNested: {
636
    // FIXME: Should allocate from normal heap so that we can free this later.
637
999
    auto *Saved = new (Context) DFIDeducedMismatchArgs;
638
999
    Saved->FirstArg = Info.FirstArg;
639
999
    Saved->SecondArg = Info.SecondArg;
640
999
    Saved->TemplateArgs = Info.take();
641
999
    Saved->CallArgIndex = Info.CallArgIndex;
642
999
    Result.Data = Saved;
643
999
    break;
644
998
  }
645
646
963k
  case Sema::TDK_NonDeducedMismatch: {
647
    // FIXME: Should allocate from normal heap so that we can free this later.
648
963k
    DFIArguments *Saved = new (Context) DFIArguments;
649
963k
    Saved->FirstArg = Info.FirstArg;
650
963k
    Saved->SecondArg = Info.SecondArg;
651
963k
    Result.Data = Saved;
652
963k
    break;
653
998
  }
654
655
9
  case Sema::TDK_IncompletePack:
656
    // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657
23.1k
  case Sema::TDK_Inconsistent:
658
82.9k
  case Sema::TDK_Underqualified: {
659
    // FIXME: Should allocate from normal heap so that we can free this later.
660
82.9k
    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661
82.9k
    Saved->Param = Info.Param;
662
82.9k
    Saved->FirstArg = Info.FirstArg;
663
82.9k
    Saved->SecondArg = Info.SecondArg;
664
82.9k
    Result.Data = Saved;
665
82.9k
    break;
666
23.1k
  }
667
668
114k
  case Sema::TDK_SubstitutionFailure:
669
114k
    Result.Data = Info.take();
670
114k
    if (Info.hasSFINAEDiagnostic()) {
671
114k
      PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672
114k
          SourceLocation(), PartialDiagnostic::NullDiagnostic());
673
114k
      Info.takeSFINAEDiagnostic(*Diag);
674
114k
      Result.HasDiagnostic = true;
675
114k
    }
676
114k
    break;
677
678
118
  case Sema::TDK_ConstraintsNotSatisfied: {
679
118
    CNSInfo *Saved = new (Context) CNSInfo;
680
118
    Saved->TemplateArgs = Info.take();
681
118
    Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682
118
    Result.Data = Saved;
683
118
    break;
684
23.1k
  }
685
686
0
  case Sema::TDK_Success:
687
0
  case Sema::TDK_NonDependentConversionFailure:
688
0
    llvm_unreachable("not a deduction failure");
689
1.37M
  }
690
691
1.37M
  return Result;
692
1.37M
}
693
694
1.37M
void DeductionFailureInfo::Destroy() {
695
1.37M
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696
0
  case Sema::TDK_Success:
697
16
  case Sema::TDK_Invalid:
698
2.26k
  case Sema::TDK_InstantiationDepth:
699
15.0k
  case Sema::TDK_Incomplete:
700
47.4k
  case Sema::TDK_TooManyArguments:
701
196k
  case Sema::TDK_TooFewArguments:
702
198k
  case Sema::TDK_InvalidExplicitArguments:
703
198k
  case Sema::TDK_CUDATargetMismatch:
704
198k
  case Sema::TDK_NonDependentConversionFailure:
705
198k
    break;
706
707
9
  case Sema::TDK_IncompletePack:
708
23.1k
  case Sema::TDK_Inconsistent:
709
82.9k
  case Sema::TDK_Underqualified:
710
83.9k
  case Sema::TDK_DeducedMismatch:
711
83.9k
  case Sema::TDK_DeducedMismatchNested:
712
1.04M
  case Sema::TDK_NonDeducedMismatch:
713
    // FIXME: Destroy the data?
714
1.04M
    Data = nullptr;
715
1.04M
    break;
716
717
114k
  case Sema::TDK_SubstitutionFailure:
718
    // FIXME: Destroy the template argument list?
719
114k
    Data = nullptr;
720
114k
    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721
114k
      Diag->~PartialDiagnosticAt();
722
114k
      HasDiagnostic = false;
723
114k
    }
724
114k
    break;
725
726
118
  case Sema::TDK_ConstraintsNotSatisfied:
727
    // FIXME: Destroy the template argument list?
728
118
    Data = nullptr;
729
118
    if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730
0
      Diag->~PartialDiagnosticAt();
731
0
      HasDiagnostic = false;
732
0
    }
733
118
    break;
734
735
  // Unhandled
736
11.2k
  case Sema::TDK_MiscellaneousDeductionFailure:
737
11.2k
    break;
738
1.37M
  }
739
1.37M
}
740
741
117k
PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
742
117k
  if (HasDiagnostic)
743
117k
    return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
744
200
  return nullptr;
745
117k
}
746
747
3.37k
TemplateParameter DeductionFailureInfo::getTemplateParameter() {
748
3.37k
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749
0
  case Sema::TDK_Success:
750
11
  case Sema::TDK_Invalid:
751
43
  case Sema::TDK_InstantiationDepth:
752
106
  case Sema::TDK_TooManyArguments:
753
154
  case Sema::TDK_TooFewArguments:
754
2.59k
  case Sema::TDK_SubstitutionFailure:
755
2.60k
  case Sema::TDK_DeducedMismatch:
756
2.60k
  case Sema::TDK_DeducedMismatchNested:
757
2.82k
  case Sema::TDK_NonDeducedMismatch:
758
2.83k
  case Sema::TDK_CUDATargetMismatch:
759
2.83k
  case Sema::TDK_NonDependentConversionFailure:
760
2.89k
  case Sema::TDK_ConstraintsNotSatisfied:
761
2.89k
    return TemplateParameter();
762
763
279
  case Sema::TDK_Incomplete:
764
344
  case Sema::TDK_InvalidExplicitArguments:
765
344
    return TemplateParameter::getFromOpaqueValue(Data);
766
767
9
  case Sema::TDK_IncompletePack:
768
110
  case Sema::TDK_Inconsistent:
769
119
  case Sema::TDK_Underqualified:
770
119
    return static_cast<DFIParamWithArguments*>(Data)->Param;
771
772
  // Unhandled
773
17
  case Sema::TDK_MiscellaneousDeductionFailure:
774
17
    break;
775
3.37k
  }
776
777
17
  return TemplateParameter();
778
3.37k
}
779
780
2.51k
TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
781
2.51k
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782
0
  case Sema::TDK_Success:
783
0
  case Sema::TDK_Invalid:
784
0
  case Sema::TDK_InstantiationDepth:
785
0
  case Sema::TDK_TooManyArguments:
786
0
  case Sema::TDK_TooFewArguments:
787
0
  case Sema::TDK_Incomplete:
788
0
  case Sema::TDK_IncompletePack:
789
0
  case Sema::TDK_InvalidExplicitArguments:
790
0
  case Sema::TDK_Inconsistent:
791
0
  case Sema::TDK_Underqualified:
792
0
  case Sema::TDK_NonDeducedMismatch:
793
0
  case Sema::TDK_CUDATargetMismatch:
794
0
  case Sema::TDK_NonDependentConversionFailure:
795
0
    return nullptr;
796
797
10
  case Sema::TDK_DeducedMismatch:
798
11
  case Sema::TDK_DeducedMismatchNested:
799
11
    return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
800
801
2.44k
  case Sema::TDK_SubstitutionFailure:
802
2.44k
    return static_cast<TemplateArgumentList*>(Data);
803
804
62
  case Sema::TDK_ConstraintsNotSatisfied:
805
62
    return static_cast<CNSInfo*>(Data)->TemplateArgs;
806
807
  // Unhandled
808
0
  case Sema::TDK_MiscellaneousDeductionFailure:
809
0
    break;
810
2.51k
  }
811
812
0
  return nullptr;
813
2.51k
}
814
815
512
const TemplateArgument *DeductionFailureInfo::getFirstArg() {
816
512
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
817
0
  case Sema::TDK_Success:
818
0
  case Sema::TDK_Invalid:
819
0
  case Sema::TDK_InstantiationDepth:
820
0
  case Sema::TDK_Incomplete:
821
0
  case Sema::TDK_TooManyArguments:
822
0
  case Sema::TDK_TooFewArguments:
823
0
  case Sema::TDK_InvalidExplicitArguments:
824
0
  case Sema::TDK_SubstitutionFailure:
825
0
  case Sema::TDK_CUDATargetMismatch:
826
0
  case Sema::TDK_NonDependentConversionFailure:
827
0
  case Sema::TDK_ConstraintsNotSatisfied:
828
0
    return nullptr;
829
830
18
  case Sema::TDK_IncompletePack:
831
278
  case Sema::TDK_Inconsistent:
832
287
  case Sema::TDK_Underqualified:
833
297
  case Sema::TDK_DeducedMismatch:
834
298
  case Sema::TDK_DeducedMismatchNested:
835
512
  case Sema::TDK_NonDeducedMismatch:
836
512
    return &static_cast<DFIArguments*>(Data)->FirstArg;
837
838
  // Unhandled
839
0
  case Sema::TDK_MiscellaneousDeductionFailure:
840
0
    break;
841
512
  }
842
843
0
  return nullptr;
844
512
}
845
846
466
const TemplateArgument *DeductionFailureInfo::getSecondArg() {
847
466
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
848
0
  case Sema::TDK_Success:
849
0
  case Sema::TDK_Invalid:
850
0
  case Sema::TDK_InstantiationDepth:
851
0
  case Sema::TDK_Incomplete:
852
0
  case Sema::TDK_IncompletePack:
853
0
  case Sema::TDK_TooManyArguments:
854
0
  case Sema::TDK_TooFewArguments:
855
0
  case Sema::TDK_InvalidExplicitArguments:
856
0
  case Sema::TDK_SubstitutionFailure:
857
0
  case Sema::TDK_CUDATargetMismatch:
858
0
  case Sema::TDK_NonDependentConversionFailure:
859
0
  case Sema::TDK_ConstraintsNotSatisfied:
860
0
    return nullptr;
861
862
232
  case Sema::TDK_Inconsistent:
863
241
  case Sema::TDK_Underqualified:
864
251
  case Sema::TDK_DeducedMismatch:
865
252
  case Sema::TDK_DeducedMismatchNested:
866
466
  case Sema::TDK_NonDeducedMismatch:
867
466
    return &static_cast<DFIArguments*>(Data)->SecondArg;
868
869
  // Unhandled
870
0
  case Sema::TDK_MiscellaneousDeductionFailure:
871
0
    break;
872
466
  }
873
874
0
  return nullptr;
875
466
}
876
877
11
llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
878
11
  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
879
10
  case Sema::TDK_DeducedMismatch:
880
11
  case Sema::TDK_DeducedMismatchNested:
881
11
    return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
882
883
0
  default:
884
0
    return llvm::None;
885
11
  }
886
11
}
887
888
bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
889
1.14M
    OverloadedOperatorKind Op) {
890
1.14M
  if (!AllowRewrittenCandidates)
891
1.13M
    return false;
892
5.67k
  return Op == OO_EqualEqual || 
Op == OO_Spaceship4.37k
;
893
1.14M
}
894
895
bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
896
1.01M
    ASTContext &Ctx, const FunctionDecl *FD) {
897
1.01M
  if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
898
1.01M
    return false;
899
  // Don't bother adding a reversed candidate that can never be a better
900
  // match than the non-reversed version.
901
1.21k
  return FD->getNumParams() != 2 ||
902
1.21k
         !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
903
1.21k
                                     FD->getParamDecl(1)->getType()) ||
904
1.21k
         
FD->hasAttr<EnableIfAttr>()600
;
905
1.01M
}
906
907
18.6M
void OverloadCandidateSet::destroyCandidates() {
908
33.4M
  for (iterator i = begin(), e = end(); i != e; 
++i14.8M
) {
909
14.8M
    for (auto &C : i->Conversions)
910
24.5M
      C.~ImplicitConversionSequence();
911
14.8M
    if (!i->Viable && 
i->FailureKind == ovl_fail_bad_deduction7.86M
)
912
914k
      i->DeductionFailure.Destroy();
913
14.8M
  }
914
18.6M
}
915
916
1.55M
void OverloadCandidateSet::clear(CandidateSetKind CSK) {
917
1.55M
  destroyCandidates();
918
1.55M
  SlabAllocator.Reset();
919
1.55M
  NumInlineBytesUsed = 0;
920
1.55M
  Candidates.clear();
921
1.55M
  Functions.clear();
922
1.55M
  Kind = CSK;
923
1.55M
}
924
925
namespace {
926
  class UnbridgedCastsSet {
927
    struct Entry {
928
      Expr **Addr;
929
      Expr *Saved;
930
    };
931
    SmallVector<Entry, 2> Entries;
932
933
  public:
934
7
    void save(Sema &S, Expr *&E) {
935
7
      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
936
0
      Entry entry = { &E, E };
937
7
      Entries.push_back(entry);
938
7
      E = S.stripARCUnbridgedCast(E);
939
7
    }
940
941
877k
    void restore() {
942
877k
      for (SmallVectorImpl<Entry>::iterator
943
877k
             i = Entries.begin(), e = Entries.end(); i != e; 
++i7
)
944
7
        *i->Addr = i->Saved;
945
877k
    }
946
  };
947
}
948
949
/// checkPlaceholderForOverload - Do any interesting placeholder-like
950
/// preprocessing on the given expression.
951
///
952
/// \param unbridgedCasts a collection to which to add unbridged casts;
953
///   without this, they will be immediately diagnosed as errors
954
///
955
/// Return true on unrecoverable error.
956
static bool
957
checkPlaceholderForOverload(Sema &S, Expr *&E,
958
8.84M
                            UnbridgedCastsSet *unbridgedCasts = nullptr) {
959
8.84M
  if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
960
    // We can't handle overloaded expressions here because overload
961
    // resolution might reasonably tweak them.
962
992
    if (placeholder->getKind() == BuiltinType::Overload) 
return false979
;
963
964
    // If the context potentially accepts unbridged ARC casts, strip
965
    // the unbridged cast and add it to the collection for later restoration.
966
13
    if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
967
13
        
unbridgedCasts7
) {
968
7
      unbridgedCasts->save(S, E);
969
7
      return false;
970
7
    }
971
972
    // Go ahead and check everything else.
973
6
    ExprResult result = S.CheckPlaceholderExpr(E);
974
6
    if (result.isInvalid())
975
0
      return true;
976
977
6
    E = result.get();
978
6
    return false;
979
6
  }
980
981
  // Nothing to do.
982
8.84M
  return false;
983
8.84M
}
984
985
/// checkArgPlaceholdersForOverload - Check a set of call operands for
986
/// placeholders.
987
static bool checkArgPlaceholdersForOverload(Sema &S,
988
                                            MultiExprArg Args,
989
878k
                                            UnbridgedCastsSet &unbridged) {
990
1.82M
  for (unsigned i = 0, e = Args.size(); i != e; 
++i950k
)
991
950k
    if (checkPlaceholderForOverload(S, Args[i], &unbridged))
992
0
      return true;
993
994
878k
  return false;
995
878k
}
996
997
/// Determine whether the given New declaration is an overload of the
998
/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
999
/// New and Old cannot be overloaded, e.g., if New has the same signature as
1000
/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1001
/// functions (or function templates) at all. When it does return Ovl_Match or
1002
/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1003
/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1004
/// declaration.
1005
///
1006
/// Example: Given the following input:
1007
///
1008
///   void f(int, float); // #1
1009
///   void f(int, int); // #2
1010
///   int f(int, int); // #3
1011
///
1012
/// When we process #1, there is no previous declaration of "f", so IsOverload
1013
/// will not be used.
1014
///
1015
/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1016
/// the parameter types, we see that #1 and #2 are overloaded (since they have
1017
/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1018
/// unchanged.
1019
///
1020
/// When we process #3, Old is an overload set containing #1 and #2. We compare
1021
/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1022
/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1023
/// functions are not part of the signature), IsOverload returns Ovl_Match and
1024
/// MatchedDecl will be set to point to the FunctionDecl for #2.
1025
///
1026
/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1027
/// by a using declaration. The rules for whether to hide shadow declarations
1028
/// ignore some properties which otherwise figure into a function template's
1029
/// signature.
1030
Sema::OverloadKind
1031
Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1032
10.8M
                    NamedDecl *&Match, bool NewIsUsingDecl) {
1033
10.8M
  for (LookupResult::iterator I = Old.begin(), E = Old.end();
1034
78.1M
         I != E; 
++I67.3M
) {
1035
67.5M
    NamedDecl *OldD = *I;
1036
1037
67.5M
    bool OldIsUsingDecl = false;
1038
67.5M
    if (isa<UsingShadowDecl>(OldD)) {
1039
11.8k
      OldIsUsingDecl = true;
1040
1041
      // We can always introduce two using declarations into the same
1042
      // context, even if they have identical signatures.
1043
11.8k
      if (NewIsUsingDecl) 
continue479
;
1044
1045
11.3k
      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1046
11.3k
    }
1047
1048
    // A using-declaration does not conflict with another declaration
1049
    // if one of them is hidden.
1050
67.5M
    if ((OldIsUsingDecl || 
NewIsUsingDecl67.5M
) &&
!isVisible(*I)11.9k
)
1051
0
      continue;
1052
1053
    // If either declaration was introduced by a using declaration,
1054
    // we'll need to use slightly different rules for matching.
1055
    // Essentially, these rules are the normal rules, except that
1056
    // function templates hide function templates with different
1057
    // return types or template parameter lists.
1058
67.5M
    bool UseMemberUsingDeclRules =
1059
67.5M
      (OldIsUsingDecl || 
NewIsUsingDecl67.5M
) &&
CurContext->isRecord()11.9k
&&
1060
67.5M
      
!New->getFriendObjectKind()8.11k
;
1061
1062
67.5M
    if (FunctionDecl *OldF = OldD->getAsFunction()) {
1063
67.5M
      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1064
216k
        if (UseMemberUsingDeclRules && 
OldIsUsingDecl321
) {
1065
298
          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1066
298
          continue;
1067
298
        }
1068
1069
215k
        if (!isa<FunctionTemplateDecl>(OldD) &&
1070
215k
            
!shouldLinkPossiblyHiddenDecl(*I, New)168k
)
1071
0
          continue;
1072
1073
215k
        Match = *I;
1074
215k
        return Ovl_Match;
1075
215k
      }
1076
1077
      // Builtins that have custom typechecking or have a reference should
1078
      // not be overloadable or redeclarable.
1079
67.3M
      if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1080
3
        Match = *I;
1081
3
        return Ovl_NonFunction;
1082
3
      }
1083
67.3M
    } else 
if (364
isa<UsingDecl>(OldD)364
||
isa<UsingPackDecl>(OldD)224
) {
1084
      // We can overload with these, which can show up when doing
1085
      // redeclaration checks for UsingDecls.
1086
140
      assert(Old.getLookupKind() == LookupUsingDeclName);
1087
224
    } else if (isa<TagDecl>(OldD)) {
1088
      // We can always overload with tags by hiding them.
1089
222
    } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1090
      // Optimistically assume that an unresolved using decl will
1091
      // overload; if it doesn't, we'll have to diagnose during
1092
      // template instantiation.
1093
      //
1094
      // Exception: if the scope is dependent and this is not a class
1095
      // member, the using declaration can only introduce an enumerator.
1096
199
      if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1097
5
        Match = *I;
1098
5
        return Ovl_NonFunction;
1099
5
      }
1100
199
    } else {
1101
      // (C++ 13p1):
1102
      //   Only function declarations can be overloaded; object and type
1103
      //   declarations cannot be overloaded.
1104
23
      Match = *I;
1105
23
      return Ovl_NonFunction;
1106
23
    }
1107
67.5M
  }
1108
1109
  // C++ [temp.friend]p1:
1110
  //   For a friend function declaration that is not a template declaration:
1111
  //    -- if the name of the friend is a qualified or unqualified template-id,
1112
  //       [...], otherwise
1113
  //    -- if the name of the friend is a qualified-id and a matching
1114
  //       non-template function is found in the specified class or namespace,
1115
  //       the friend declaration refers to that function, otherwise,
1116
  //    -- if the name of the friend is a qualified-id and a matching function
1117
  //       template is found in the specified class or namespace, the friend
1118
  //       declaration refers to the deduced specialization of that function
1119
  //       template, otherwise
1120
  //    -- the name shall be an unqualified-id [...]
1121
  // If we get here for a qualified friend declaration, we've just reached the
1122
  // third bullet. If the type of the friend is dependent, skip this lookup
1123
  // until instantiation.
1124
10.6M
  if (New->getFriendObjectKind() && 
New->getQualifier()24.1k
&&
1125
10.6M
      
!New->getDescribedFunctionTemplate()72
&&
1126
10.6M
      
!New->getDependentSpecializationInfo()52
&&
1127
10.6M
      
!New->getType()->isDependentType()42
) {
1128
37
    LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1129
37
    TemplateSpecResult.addAllDecls(Old);
1130
37
    if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1131
37
                                            /*QualifiedFriend*/true)) {
1132
21
      New->setInvalidDecl();
1133
21
      return Ovl_Overload;
1134
21
    }
1135
1136
16
    Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1137
16
    return Ovl_Match;
1138
37
  }
1139
1140
10.6M
  return Ovl_Overload;
1141
10.6M
}
1142
1143
bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1144
                      bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1145
67.5M
                      bool ConsiderRequiresClauses) {
1146
  // C++ [basic.start.main]p2: This function shall not be overloaded.
1147
67.5M
  if (New->isMain())
1148
17
    return false;
1149
1150
  // MSVCRT user defined entry points cannot be overloaded.
1151
67.5M
  if (New->isMSVCRTEntryPoint())
1152
1
    return false;
1153
1154
67.5M
  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1155
67.5M
  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1156
1157
  // C++ [temp.fct]p2:
1158
  //   A function template can be overloaded with other function templates
1159
  //   and with normal (non-template) functions.
1160
67.5M
  if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1161
1.44M
    return true;
1162
1163
  // Is the function New an overload of the function Old?
1164
66.1M
  QualType OldQType = Context.getCanonicalType(Old->getType());
1165
66.1M
  QualType NewQType = Context.getCanonicalType(New->getType());
1166
1167
  // Compare the signatures (C++ 1.3.10) of the two functions to
1168
  // determine whether they are overloads. If we find any mismatch
1169
  // in the signature, they are overloads.
1170
1171
  // If either of these functions is a K&R-style function (no
1172
  // prototype), then we consider them to have matching signatures.
1173
66.1M
  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1174
66.1M
      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1175
0
    return false;
1176
1177
66.1M
  const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1178
66.1M
  const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1179
1180
  // The signature of a function includes the types of its
1181
  // parameters (C++ 1.3.10), which includes the presence or absence
1182
  // of the ellipsis; see C++ DR 357).
1183
66.1M
  if (OldQType != NewQType &&
1184
66.1M
      
(65.8M
OldType->getNumParams() != NewType->getNumParams()65.8M
||
1185
65.8M
       
OldType->isVariadic() != NewType->isVariadic()64.3M
||
1186
65.8M
       
!FunctionParamTypesAreEqual(OldType, NewType)64.3M
))
1187
65.7M
    return true;
1188
1189
  // C++ [temp.over.link]p4:
1190
  //   The signature of a function template consists of its function
1191
  //   signature, its return type and its template parameter list. The names
1192
  //   of the template parameters are significant only for establishing the
1193
  //   relationship between the template parameters and the rest of the
1194
  //   signature.
1195
  //
1196
  // We check the return type and template parameter lists for function
1197
  // templates first; the remaining checks follow.
1198
  //
1199
  // However, we don't consider either of these when deciding whether
1200
  // a member introduced by a shadow declaration is hidden.
1201
400k
  if (!UseMemberUsingDeclRules && 
NewTemplate399k
&&
1202
400k
      
(106k
!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1203
106k
                                       OldTemplate->getTemplateParameters(),
1204
106k
                                       false, TPL_TemplateMatch) ||
1205
106k
       !Context.hasSameType(Old->getDeclaredReturnType(),
1206
71.9k
                            New->getDeclaredReturnType())))
1207
58.9k
    return true;
1208
1209
  // If the function is a class member, its signature includes the
1210
  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1211
  //
1212
  // As part of this, also check whether one of the member functions
1213
  // is static, in which case they are not overloads (C++
1214
  // 13.1p2). While not part of the definition of the signature,
1215
  // this check is important to determine whether these functions
1216
  // can be overloaded.
1217
341k
  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1218
341k
  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1219
341k
  if (OldMethod && 
NewMethod268k
&&
1220
341k
      
!OldMethod->isStatic()268k
&&
!NewMethod->isStatic()258k
) {
1221
258k
    if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1222
381
      if (!UseMemberUsingDeclRules &&
1223
381
          (OldMethod->getRefQualifier() == RQ_None ||
1224
381
           
NewMethod->getRefQualifier() == RQ_None380
)) {
1225
        // C++0x [over.load]p2:
1226
        //   - Member function declarations with the same name and the same
1227
        //     parameter-type-list as well as member function template
1228
        //     declarations with the same name, the same parameter-type-list, and
1229
        //     the same template parameter lists cannot be overloaded if any of
1230
        //     them, but not all, have a ref-qualifier (8.3.5).
1231
11
        Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1232
11
          << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1233
11
        Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1234
11
      }
1235
381
      return true;
1236
381
    }
1237
1238
    // We may not have applied the implicit const for a constexpr member
1239
    // function yet (because we haven't yet resolved whether this is a static
1240
    // or non-static member function). Add it now, on the assumption that this
1241
    // is a redeclaration of OldMethod.
1242
258k
    auto OldQuals = OldMethod->getMethodQualifiers();
1243
258k
    auto NewQuals = NewMethod->getMethodQualifiers();
1244
258k
    if (!getLangOpts().CPlusPlus14 && 
NewMethod->isConstexpr()235k
&&
1245
258k
        
!isa<CXXConstructorDecl>(NewMethod)18.3k
)
1246
17.2k
      NewQuals.addConst();
1247
    // We do not allow overloading based off of '__restrict'.
1248
258k
    OldQuals.removeRestrict();
1249
258k
    NewQuals.removeRestrict();
1250
258k
    if (OldQuals != NewQuals)
1251
87.1k
      return true;
1252
258k
  }
1253
1254
  // Though pass_object_size is placed on parameters and takes an argument, we
1255
  // consider it to be a function-level modifier for the sake of function
1256
  // identity. Either the function has one or more parameters with
1257
  // pass_object_size or it doesn't.
1258
253k
  if (functionHasPassObjectSizeParams(New) !=
1259
253k
      functionHasPassObjectSizeParams(Old))
1260
16
    return true;
1261
1262
  // enable_if attributes are an order-sensitive part of the signature.
1263
253k
  for (specific_attr_iterator<EnableIfAttr>
1264
253k
         NewI = New->specific_attr_begin<EnableIfAttr>(),
1265
253k
         NewE = New->specific_attr_end<EnableIfAttr>(),
1266
253k
         OldI = Old->specific_attr_begin<EnableIfAttr>(),
1267
253k
         OldE = Old->specific_attr_end<EnableIfAttr>();
1268
253k
       NewI != NewE || 
OldI != OldE249k
;
++NewI, ++OldI12
) {
1269
4.66k
    if (NewI == NewE || 
OldI == OldE4.65k
)
1270
4.60k
      return true;
1271
62
    llvm::FoldingSetNodeID NewID, OldID;
1272
62
    NewI->getCond()->Profile(NewID, Context, true);
1273
62
    OldI->getCond()->Profile(OldID, Context, true);
1274
62
    if (NewID != OldID)
1275
50
      return true;
1276
62
  }
1277
1278
249k
  if (getLangOpts().CUDA && 
ConsiderCudaAttrs378
) {
1279
    // Don't allow overloading of destructors.  (In theory we could, but it
1280
    // would be a giant change to clang.)
1281
362
    if (!isa<CXXDestructorDecl>(New)) {
1282
352
      CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1283
352
                         OldTarget = IdentifyCUDATarget(Old);
1284
352
      if (NewTarget != CFT_InvalidTarget) {
1285
352
        assert((OldTarget != CFT_InvalidTarget) &&
1286
352
               "Unexpected invalid target.");
1287
1288
        // Allow overloading of functions with same signature and different CUDA
1289
        // target attributes.
1290
352
        if (NewTarget != OldTarget)
1291
309
          return true;
1292
352
      }
1293
352
    }
1294
362
  }
1295
1296
248k
  if (ConsiderRequiresClauses) {
1297
216k
    Expr *NewRC = New->getTrailingRequiresClause(),
1298
216k
         *OldRC = Old->getTrailingRequiresClause();
1299
216k
    if ((NewRC != nullptr) != (OldRC != nullptr))
1300
      // RC are most certainly different - these are overloads.
1301
10
      return true;
1302
1303
216k
    if (NewRC) {
1304
41
      llvm::FoldingSetNodeID NewID, OldID;
1305
41
      NewRC->Profile(NewID, Context, /*Canonical=*/true);
1306
41
      OldRC->Profile(OldID, Context, /*Canonical=*/true);
1307
41
      if (NewID != OldID)
1308
        // RCs are not equivalent - these are overloads.
1309
41
        return true;
1310
41
    }
1311
216k
  }
1312
1313
  // The signatures match; this is not an overload.
1314
248k
  return false;
1315
248k
}
1316
1317
/// Tries a user-defined conversion from From to ToType.
1318
///
1319
/// Produces an implicit conversion sequence for when a standard conversion
1320
/// is not an option. See TryImplicitConversion for more information.
1321
static ImplicitConversionSequence
1322
TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1323
                         bool SuppressUserConversions,
1324
                         AllowedExplicit AllowExplicit,
1325
                         bool InOverloadResolution,
1326
                         bool CStyle,
1327
                         bool AllowObjCWritebackConversion,
1328
1.40M
                         bool AllowObjCConversionOnExplicit) {
1329
1.40M
  ImplicitConversionSequence ICS;
1330
1331
1.40M
  if (SuppressUserConversions) {
1332
    // We're not in the case above, so there is no conversion that
1333
    // we can perform.
1334
214k
    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335
214k
    return ICS;
1336
214k
  }
1337
1338
  // Attempt user-defined conversion.
1339
1.19M
  OverloadCandidateSet Conversions(From->getExprLoc(),
1340
1.19M
                                   OverloadCandidateSet::CSK_Normal);
1341
1.19M
  switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1342
1.19M
                                  Conversions, AllowExplicit,
1343
1.19M
                                  AllowObjCConversionOnExplicit)) {
1344
425k
  case OR_Success:
1345
425k
  case OR_Deleted:
1346
425k
    ICS.setUserDefined();
1347
    // C++ [over.ics.user]p4:
1348
    //   A conversion of an expression of class type to the same class
1349
    //   type is given Exact Match rank, and a conversion of an
1350
    //   expression of class type to a base class of that type is
1351
    //   given Conversion rank, in spite of the fact that a copy
1352
    //   constructor (i.e., a user-defined conversion function) is
1353
    //   called for those cases.
1354
425k
    if (CXXConstructorDecl *Constructor
1355
425k
          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1356
30.3k
      QualType FromCanon
1357
30.3k
        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1358
30.3k
      QualType ToCanon
1359
30.3k
        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1360
30.3k
      if (Constructor->isCopyConstructor() &&
1361
30.3k
          
(4
FromCanon == ToCanon4
||
1362
4
           S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1363
        // Turn this into a "standard" conversion sequence, so that it
1364
        // gets ranked with standard conversion sequences.
1365
0
        DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1366
0
        ICS.setStandard();
1367
0
        ICS.Standard.setAsIdentityConversion();
1368
0
        ICS.Standard.setFromType(From->getType());
1369
0
        ICS.Standard.setAllToTypes(ToType);
1370
0
        ICS.Standard.CopyConstructor = Constructor;
1371
0
        ICS.Standard.FoundCopyConstructor = Found;
1372
0
        if (ToCanon != FromCanon)
1373
0
          ICS.Standard.Second = ICK_Derived_To_Base;
1374
0
      }
1375
30.3k
    }
1376
425k
    break;
1377
1378
7.97k
  case OR_Ambiguous:
1379
7.97k
    ICS.setAmbiguous();
1380
7.97k
    ICS.Ambiguous.setFromType(From->getType());
1381
7.97k
    ICS.Ambiguous.setToType(ToType);
1382
7.97k
    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1383
24.2k
         Cand != Conversions.end(); 
++Cand16.2k
)
1384
16.2k
      if (Cand->Best)
1385
15.9k
        ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1386
7.97k
    break;
1387
1388
    // Fall through.
1389
756k
  case OR_No_Viable_Function:
1390
756k
    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1391
756k
    break;
1392
1.19M
  }
1393
1394
1.19M
  return ICS;
1395
1.19M
}
1396
1397
/// TryImplicitConversion - Attempt to perform an implicit conversion
1398
/// from the given expression (Expr) to the given type (ToType). This
1399
/// function returns an implicit conversion sequence that can be used
1400
/// to perform the initialization. Given
1401
///
1402
///   void f(float f);
1403
///   void g(int i) { f(i); }
1404
///
1405
/// this routine would produce an implicit conversion sequence to
1406
/// describe the initialization of f from i, which will be a standard
1407
/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1408
/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1409
//
1410
/// Note that this routine only determines how the conversion can be
1411
/// performed; it does not actually perform the conversion. As such,
1412
/// it will not produce any diagnostics if no conversion is available,
1413
/// but will instead return an implicit conversion sequence of kind
1414
/// "BadConversion".
1415
///
1416
/// If @p SuppressUserConversions, then user-defined conversions are
1417
/// not permitted.
1418
/// If @p AllowExplicit, then explicit user-defined conversions are
1419
/// permitted.
1420
///
1421
/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1422
/// writeback conversion, which allows __autoreleasing id* parameters to
1423
/// be initialized with __strong id* or __weak id* arguments.
1424
static ImplicitConversionSequence
1425
TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1426
                      bool SuppressUserConversions,
1427
                      AllowedExplicit AllowExplicit,
1428
                      bool InOverloadResolution,
1429
                      bool CStyle,
1430
                      bool AllowObjCWritebackConversion,
1431
23.8M
                      bool AllowObjCConversionOnExplicit) {
1432
23.8M
  ImplicitConversionSequence ICS;
1433
23.8M
  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1434
23.8M
                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1435
21.8M
    ICS.setStandard();
1436
21.8M
    return ICS;
1437
21.8M
  }
1438
1439
2.07M
  if (!S.getLangOpts().CPlusPlus) {
1440
623k
    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1441
623k
    return ICS;
1442
623k
  }
1443
1444
  // C++ [over.ics.user]p4:
1445
  //   A conversion of an expression of class type to the same class
1446
  //   type is given Exact Match rank, and a conversion of an
1447
  //   expression of class type to a base class of that type is
1448
  //   given Conversion rank, in spite of the fact that a copy/move
1449
  //   constructor (i.e., a user-defined conversion function) is
1450
  //   called for those cases.
1451
1.44M
  QualType FromType = From->getType();
1452
1.44M
  if (ToType->getAs<RecordType>() && 
FromType->getAs<RecordType>()275k
&&
1453
1.44M
      
(164k
S.Context.hasSameUnqualifiedType(FromType, ToType)164k
||
1454
164k
       
S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType)118k
)) {
1455
46.5k
    ICS.setStandard();
1456
46.5k
    ICS.Standard.setAsIdentityConversion();
1457
46.5k
    ICS.Standard.setFromType(FromType);
1458
46.5k
    ICS.Standard.setAllToTypes(ToType);
1459
1460
    // We don't actually check at this point whether there is a valid
1461
    // copy/move constructor, since overloading just assumes that it
1462
    // exists. When we actually perform initialization, we'll find the
1463
    // appropriate constructor to copy the returned object, if needed.
1464
46.5k
    ICS.Standard.CopyConstructor = nullptr;
1465
1466
    // Determine whether this is considered a derived-to-base conversion.
1467
46.5k
    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1468
634
      ICS.Standard.Second = ICK_Derived_To_Base;
1469
1470
46.5k
    return ICS;
1471
46.5k
  }
1472
1473
1.40M
  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1474
1.40M
                                  AllowExplicit, InOverloadResolution, CStyle,
1475
1.40M
                                  AllowObjCWritebackConversion,
1476
1.40M
                                  AllowObjCConversionOnExplicit);
1477
1.44M
}
1478
1479
ImplicitConversionSequence
1480
Sema::TryImplicitConversion(Expr *From, QualType ToType,
1481
                            bool SuppressUserConversions,
1482
                            AllowedExplicit AllowExplicit,
1483
                            bool InOverloadResolution,
1484
                            bool CStyle,
1485
4.36M
                            bool AllowObjCWritebackConversion) {
1486
4.36M
  return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1487
4.36M
                                 AllowExplicit, InOverloadResolution, CStyle,
1488
4.36M
                                 AllowObjCWritebackConversion,
1489
4.36M
                                 /*AllowObjCConversionOnExplicit=*/false);
1490
4.36M
}
1491
1492
/// PerformImplicitConversion - Perform an implicit conversion of the
1493
/// expression From to the type ToType. Returns the
1494
/// converted expression. Flavor is the kind of conversion we're
1495
/// performing, used in the error message. If @p AllowExplicit,
1496
/// explicit user-defined conversions are permitted.
1497
ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1498
                                           AssignmentAction Action,
1499
3.01M
                                           bool AllowExplicit) {
1500
3.01M
  if (checkPlaceholderForOverload(*this, From))
1501
0
    return ExprError();
1502
1503
  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1504
3.01M
  bool AllowObjCWritebackConversion
1505
3.01M
    = getLangOpts().ObjCAutoRefCount &&
1506
3.01M
      
(854
Action == AA_Passing854
||
Action == AA_Sending854
);
1507
3.01M
  if (getLangOpts().ObjC)
1508
49.8k
    CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1509
49.8k
                                      From->getType(), From);
1510
3.01M
  ImplicitConversionSequence ICS = ::TryImplicitConversion(
1511
3.01M
      *this, From, ToType,
1512
3.01M
      /*SuppressUserConversions=*/false,
1513
3.01M
      AllowExplicit ? 
AllowedExplicit::All1.80M
:
AllowedExplicit::None1.21M
,
1514
3.01M
      /*InOverloadResolution=*/false,
1515
3.01M
      /*CStyle=*/false, AllowObjCWritebackConversion,
1516
3.01M
      /*AllowObjCConversionOnExplicit=*/false);
1517
3.01M
  return PerformImplicitConversion(From, ToType, ICS, Action);
1518
3.01M
}
1519
1520
/// Determine whether the conversion from FromType to ToType is a valid
1521
/// conversion that strips "noexcept" or "noreturn" off the nested function
1522
/// type.
1523
bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1524
22.8M
                                QualType &ResultTy) {
1525
22.8M
  if (Context.hasSameUnqualifiedType(FromType, ToType))
1526
21.6M
    return false;
1527
1528
  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1529
  //                    or F(t noexcept) -> F(t)
1530
  // where F adds one of the following at most once:
1531
  //   - a pointer
1532
  //   - a member pointer
1533
  //   - a block pointer
1534
  // Changes here need matching changes in FindCompositePointerType.
1535
1.18M
  CanQualType CanTo = Context.getCanonicalType(ToType);
1536
1.18M
  CanQualType CanFrom = Context.getCanonicalType(FromType);
1537
1.18M
  Type::TypeClass TyClass = CanTo->getTypeClass();
1538
1.18M
  if (TyClass != CanFrom->getTypeClass()) 
return false222k
;
1539
958k
  if (TyClass != Type::FunctionProto && 
TyClass != Type::FunctionNoProto943k
) {
1540
943k
    if (TyClass == Type::Pointer) {
1541
334k
      CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1542
334k
      CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1543
608k
    } else if (TyClass == Type::BlockPointer) {
1544
12
      CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1545
12
      CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1546
608k
    } else if (TyClass == Type::MemberPointer) {
1547
696
      auto ToMPT = CanTo.castAs<MemberPointerType>();
1548
696
      auto FromMPT = CanFrom.castAs<MemberPointerType>();
1549
      // A function pointer conversion cannot change the class of the function.
1550
696
      if (ToMPT->getClass() != FromMPT->getClass())
1551
160
        return false;
1552
536
      CanTo = ToMPT->getPointeeType();
1553
536
      CanFrom = FromMPT->getPointeeType();
1554
607k
    } else {
1555
607k
      return false;
1556
607k
    }
1557
1558
335k
    TyClass = CanTo->getTypeClass();
1559
335k
    if (TyClass != CanFrom->getTypeClass()) 
return false104k
;
1560
231k
    if (TyClass != Type::FunctionProto && 
TyClass != Type::FunctionNoProto229k
)
1561
229k
      return false;
1562
231k
  }
1563
1564
16.5k
  const auto *FromFn = cast<FunctionType>(CanFrom);
1565
16.5k
  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1566
1567
16.5k
  const auto *ToFn = cast<FunctionType>(CanTo);
1568
16.5k
  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1569
1570
16.5k
  bool Changed = false;
1571
1572
  // Drop 'noreturn' if not present in target type.
1573
16.5k
  if (FromEInfo.getNoReturn() && 
!ToEInfo.getNoReturn()119
) {
1574
110
    FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1575
110
    Changed = true;
1576
110
  }
1577
1578
  // Drop 'noexcept' if not present in target type.
1579
16.5k
  if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1580
16.5k
    const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1581
16.5k
    if (FromFPT->isNothrow() && 
!ToFPT->isNothrow()981
) {
1582
979
      FromFn = cast<FunctionType>(
1583
979
          Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1584
979
                                                   EST_None)
1585
979
                 .getTypePtr());
1586
979
      Changed = true;
1587
979
    }
1588
1589
    // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1590
    // only if the ExtParameterInfo lists of the two function prototypes can be
1591
    // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1592
16.5k
    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1593
16.5k
    bool CanUseToFPT, CanUseFromFPT;
1594
16.5k
    if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1595
16.5k
                                      CanUseFromFPT, NewParamInfos) &&
1596
16.5k
        
CanUseToFPT16.5k
&&
!CanUseFromFPT16.5k
) {
1597
6
      FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1598
6
      ExtInfo.ExtParameterInfos =
1599
6
          NewParamInfos.empty() ? nullptr : 
NewParamInfos.data()0
;
1600
6
      QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1601
6
                                            FromFPT->getParamTypes(), ExtInfo);
1602
6
      FromFn = QT->getAs<FunctionType>();
1603
6
      Changed = true;
1604
6
    }
1605
16.5k
  }
1606
1607
16.5k
  if (!Changed)
1608
15.5k
    return false;
1609
1610
1.09k
  assert(QualType(FromFn, 0).isCanonical());
1611
1.09k
  if (QualType(FromFn, 0) != CanTo) 
return false208
;
1612
1613
887
  ResultTy = ToType;
1614
887
  return true;
1615
1.09k
}
1616
1617
/// Determine whether the conversion from FromType to ToType is a valid
1618
/// vector conversion.
1619
///
1620
/// \param ICK Will be set to the vector conversion kind, if this is a vector
1621
/// conversion.
1622
static bool IsVectorConversion(Sema &S, QualType FromType,
1623
1.60M
                               QualType ToType, ImplicitConversionKind &ICK) {
1624
  // We need at least one of these types to be a vector type to have a vector
1625
  // conversion.
1626
1.60M
  if (!ToType->isVectorType() && 
!FromType->isVectorType()671k
)
1627
608k
    return false;
1628
1629
  // Identical types require no conversions.
1630
998k
  if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1631
0
    return false;
1632
1633
  // There are no conversions between extended vector types, only identity.
1634
998k
  if (ToType->isExtVectorType()) {
1635
    // There are no conversions between extended vector types other than the
1636
    // identity conversion.
1637
517k
    if (FromType->isExtVectorType())
1638
448k
      return false;
1639
1640
    // Vector splat from any arithmetic type to a vector.
1641
68.9k
    if (FromType->isArithmeticType()) {
1642
68.9k
      ICK = ICK_Vector_Splat;
1643
68.9k
      return true;
1644
68.9k
    }
1645
68.9k
  }
1646
1647
481k
  if (ToType->isSizelessBuiltinType() || 
FromType->isSizelessBuiltinType()480k
)
1648
551
    if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1649
551
        
S.Context.areLaxCompatibleSveTypes(FromType, ToType)414
) {
1650
297
      ICK = ICK_SVE_Vector_Conversion;
1651
297
      return true;
1652
297
    }
1653
1654
  // We can perform the conversion between vector types in the following cases:
1655
  // 1)vector types are equivalent AltiVec and GCC vector types
1656
  // 2)lax vector conversions are permitted and the vector types are of the
1657
  //   same size
1658
  // 3)the destination type does not have the ARM MVE strict-polymorphism
1659
  //   attribute, which inhibits lax vector conversion for overload resolution
1660
  //   only
1661
480k
  if (ToType->isVectorType() && 
FromType->isVectorType()418k
) {
1662
417k
    if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1663
417k
        
(346k
S.isLaxVectorConversion(FromType, ToType)346k
&&
1664
395k
         
!ToType->hasAttr(attr::ArmMveStrictPolymorphism)336k
)) {
1665
395k
      ICK = ICK_Vector_Conversion;
1666
395k
      return true;
1667
395k
    }
1668
417k
  }
1669
1670
85.2k
  return false;
1671
480k
}
1672
1673
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1674
                                bool InOverloadResolution,
1675
                                StandardConversionSequence &SCS,
1676
                                bool CStyle);
1677
1678
/// IsStandardConversion - Determines whether there is a standard
1679
/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1680
/// expression From to the type ToType. Standard conversion sequences
1681
/// only consider non-class types; for conversions that involve class
1682
/// types, use TryImplicitConversion. If a conversion exists, SCS will
1683
/// contain the standard conversion sequence required to perform this
1684
/// conversion and this routine will return true. Otherwise, this
1685
/// routine will return false and the value of SCS is unspecified.
1686
static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1687
                                 bool InOverloadResolution,
1688
                                 StandardConversionSequence &SCS,
1689
                                 bool CStyle,
1690
23.8M
                                 bool AllowObjCWritebackConversion) {
1691
23.8M
  QualType FromType = From->getType();
1692
1693
  // Standard conversions (C++ [conv])
1694
23.8M
  SCS.setAsIdentityConversion();
1695
23.8M
  SCS.IncompatibleObjC = false;
1696
23.8M
  SCS.setFromType(FromType);
1697
23.8M
  SCS.CopyConstructor = nullptr;
1698
1699
  // There are no standard conversions for class types in C++, so
1700
  // abort early. When overloading in C, however, we do permit them.
1701
23.8M
  if (S.getLangOpts().CPlusPlus &&
1702
23.8M
      
(22.6M
FromType->isRecordType()22.6M
||
ToType->isRecordType()21.6M
))
1703
1.07M
    return false;
1704
1705
  // The first conversion can be an lvalue-to-rvalue conversion,
1706
  // array-to-pointer conversion, or function-to-pointer conversion
1707
  // (C++ 4p1).
1708
1709
22.8M
  if (FromType == S.Context.OverloadTy) {
1710
3.83k
    DeclAccessPair AccessPair;
1711
3.83k
    if (FunctionDecl *Fn
1712
3.83k
          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1713
3.83k
                                                 AccessPair)) {
1714
      // We were able to resolve the address of the overloaded function,
1715
      // so we can convert to the type of that function.
1716
1.86k
      FromType = Fn->getType();
1717
1.86k
      SCS.setFromType(FromType);
1718
1719
      // we can sometimes resolve &foo<int> regardless of ToType, so check
1720
      // if the type matches (identity) or we are converting to bool
1721
1.86k
      if (!S.Context.hasSameUnqualifiedType(
1722
1.86k
                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1723
125
        QualType resultTy;
1724
        // if the function type matches except for [[noreturn]], it's ok
1725
125
        if (!S.IsFunctionConversion(FromType,
1726
125
              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1727
          // otherwise, only a boolean conversion is standard
1728
46
          if (!ToType->isBooleanType())
1729
22
            return false;
1730
125
      }
1731
1732
      // Check if the "from" expression is taking the address of an overloaded
1733
      // function and recompute the FromType accordingly. Take advantage of the
1734
      // fact that non-static member functions *must* have such an address-of
1735
      // expression.
1736
1.84k
      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1737
1.84k
      if (Method && 
!Method->isStatic()323
) {
1738
182
        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1739
182
               "Non-unary operator on non-static member address");
1740
0
        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1741
182
               == UO_AddrOf &&
1742
182
               "Non-address-of operator on non-static member address");
1743
0
        const Type *ClassType
1744
182
          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1745
182
        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1746
1.66k
      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1747
558
        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1748
558
               UO_AddrOf &&
1749
558
               "Non-address-of operator for overloaded function expression");
1750
0
        FromType = S.Context.getPointerType(FromType);
1751
558
      }
1752
1753
      // Check that we've computed the proper type after overload resolution.
1754
      // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1755
      // be calling it from within an NDEBUG block.
1756
0
      assert(S.Context.hasSameType(
1757
1.84k
        FromType,
1758
1.84k
        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1759
1.96k
    } else {
1760
1.96k
      return false;
1761
1.96k
    }
1762
3.83k
  }
1763
  // Lvalue-to-rvalue conversion (C++11 4.1):
1764
  //   A glvalue (3.10) of a non-function, non-array type T can
1765
  //   be converted to a prvalue.
1766
22.8M
  bool argIsLValue = From->isGLValue();
1767
22.8M
  if (argIsLValue &&
1768
22.8M
      
!FromType->isFunctionType()7.46M
&&
!FromType->isArrayType()7.45M
&&
1769
22.8M
      
S.Context.getCanonicalType(FromType) != S.Context.OverloadTy7.24M
) {
1770
7.24M
    SCS.First = ICK_Lvalue_To_Rvalue;
1771
1772
    // C11 6.3.2.1p2:
1773
    //   ... if the lvalue has atomic type, the value has the non-atomic version
1774
    //   of the type of the lvalue ...
1775
7.24M
    if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1776
245
      FromType = Atomic->getValueType();
1777
1778
    // If T is a non-class type, the type of the rvalue is the
1779
    // cv-unqualified version of T. Otherwise, the type of the rvalue
1780
    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1781
    // just strip the qualifiers because they don't matter.
1782
7.24M
    FromType = FromType.getUnqualifiedType();
1783
15.5M
  } else if (FromType->isArrayType()) {
1784
    // Array-to-pointer conversion (C++ 4.2)
1785
208k
    SCS.First = ICK_Array_To_Pointer;
1786
1787
    // An lvalue or rvalue of type "array of N T" or "array of unknown
1788
    // bound of T" can be converted to an rvalue of type "pointer to
1789
    // T" (C++ 4.2p1).
1790
208k
    FromType = S.Context.getArrayDecayedType(FromType);
1791
1792
208k
    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1793
      // This conversion is deprecated in C++03 (D.4)
1794
853
      SCS.DeprecatedStringLiteralToCharPtr = true;
1795
1796
      // For the purpose of ranking in overload resolution
1797
      // (13.3.3.1.1), this conversion is considered an
1798
      // array-to-pointer conversion followed by a qualification
1799
      // conversion (4.4). (C++ 4.2p2)
1800
853
      SCS.Second = ICK_Identity;
1801
853
      SCS.Third = ICK_Qualification;
1802
853
      SCS.QualificationIncludesObjCLifetime = false;
1803
853
      SCS.setAllToTypes(FromType);
1804
853
      return true;
1805
853
    }
1806
15.3M
  } else if (FromType->isFunctionType() && 
argIsLValue8.16k
) {
1807
    // Function-to-pointer conversion (C++ 4.3).
1808
8.16k
    SCS.First = ICK_Function_To_Pointer;
1809
1810
8.16k
    if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1811
6.00k
      if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1812
6.00k
        if (!S.checkAddressOfFunctionIsAvailable(FD))
1813
10
          return false;
1814
1815
    // An lvalue of function type T can be converted to an rvalue of
1816
    // type "pointer to T." The result is a pointer to the
1817
    // function. (C++ 4.3p1).
1818
8.15k
    FromType = S.Context.getPointerType(FromType);
1819
15.3M
  } else {
1820
    // We don't require any conversions for the first step.
1821
15.3M
    SCS.First = ICK_Identity;
1822
15.3M
  }
1823
22.8M
  SCS.setToType(0, FromType);
1824
1825
  // The second conversion can be an integral promotion, floating
1826
  // point promotion, integral conversion, floating point conversion,
1827
  // floating-integral conversion, pointer conversion,
1828
  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1829
  // For overloading in C, this can also be a "compatible-type"
1830
  // conversion.
1831
22.8M
  bool IncompatibleObjC = false;
1832
22.8M
  ImplicitConversionKind SecondICK = ICK_Identity;
1833
22.8M
  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1834
    // The unqualified versions of the types are the same: there's no
1835
    // conversion to do.
1836
10.8M
    SCS.Second = ICK_Identity;
1837
11.9M
  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1838
    // Integral promotion (C++ 4.5).
1839
745k
    SCS.Second = ICK_Integral_Promotion;
1840
745k
    FromType = ToType.getUnqualifiedType();
1841
11.2M
  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1842
    // Floating point promotion (C++ 4.6).
1843
5.67k
    SCS.Second = ICK_Floating_Promotion;
1844
5.67k
    FromType = ToType.getUnqualifiedType();
1845
11.2M
  } else if (S.IsComplexPromotion(FromType, ToType)) {
1846
    // Complex promotion (Clang extension)
1847
30
    SCS.Second = ICK_Complex_Promotion;
1848
30
    FromType = ToType.getUnqualifiedType();
1849
11.2M
  } else if (ToType->isBooleanType() &&
1850
11.2M
             
(145k
FromType->isArithmeticType()145k
||
1851
145k
              
FromType->isAnyPointerType()20.0k
||
1852
145k
              
FromType->isBlockPointerType()231
||
1853
145k
              
FromType->isMemberPointerType()219
)) {
1854
    // Boolean conversions (C++ 4.12).
1855
145k
    SCS.Second = ICK_Boolean_Conversion;
1856
145k
    FromType = S.Context.BoolTy;
1857
11.0M
  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1858
11.0M
             
ToType->isIntegralType(S.Context)9.30M
) {
1859
    // Integral conversions (C++ 4.7).
1860
6.90M
    SCS.Second = ICK_Integral_Conversion;
1861
6.90M
    FromType = ToType.getUnqualifiedType();
1862
6.90M
  } else 
if (4.17M
FromType->isAnyComplexType()4.17M
&&
ToType->isAnyComplexType()702
) {
1863
    // Complex conversions (C99 6.3.1.6)
1864
95
    SCS.Second = ICK_Complex_Conversion;
1865
95
    FromType = ToType.getUnqualifiedType();
1866
4.17M
  } else if ((FromType->isAnyComplexType() && 
ToType->isArithmeticType()607
) ||
1867
4.17M
             
(4.17M
ToType->isAnyComplexType()4.17M
&&
FromType->isArithmeticType()455
)) {
1868
    // Complex-real conversions (C99 6.3.1.7)
1869
1.04k
    SCS.Second = ICK_Complex_Real;
1870
1.04k
    FromType = ToType.getUnqualifiedType();
1871
4.17M
  } else if (FromType->isRealFloatingType() && 
ToType->isRealFloatingType()122k
) {
1872
    // FIXME: disable conversions between long double, __ibm128 and __float128
1873
    // if their representation is different until there is back end support
1874
    // We of course allow this conversion if long double is really double.
1875
1876
    // Conversions between bfloat and other floats are not permitted.
1877
53.4k
    if (FromType == S.Context.BFloat16Ty || 
ToType == S.Context.BFloat16Ty53.4k
)
1878
10
      return false;
1879
1880
    // Conversions between IEEE-quad and IBM-extended semantics are not
1881
    // permitted.
1882
53.4k
    const llvm::fltSemantics &FromSem =
1883
53.4k
        S.Context.getFloatTypeSemantics(FromType);
1884
53.4k
    const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1885
53.4k
    if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1886
53.4k
         
&ToSem == &llvm::APFloat::IEEEquad()19
) ||
1887
53.4k
        
(53.4k
&FromSem == &llvm::APFloat::IEEEquad()53.4k
&&
1888
53.4k
         
&ToSem == &llvm::APFloat::PPCDoubleDouble()11
))
1889
6
      return false;
1890
1891
    // Floating point conversions (C++ 4.8).
1892
53.3k
    SCS.Second = ICK_Floating_Conversion;
1893
53.3k
    FromType = ToType.getUnqualifiedType();
1894
4.12M
  } else if ((FromType->isRealFloatingType() &&
1895
4.12M
              
ToType->isIntegralType(S.Context)69.4k
) ||
1896
4.12M
             
(4.07M
FromType->isIntegralOrUnscopedEnumerationType()4.07M
&&
1897
4.07M
              
ToType->isRealFloatingType()2.40M
)) {
1898
    // Conversions between bfloat and int are not permitted.
1899
2.36M
    if (FromType->isBFloat16Type() || 
ToType->isBFloat16Type()2.36M
)
1900
38
      return false;
1901
1902
    // Floating-integral conversions (C++ 4.9).
1903
2.36M
    SCS.Second = ICK_Floating_Integral;
1904
2.36M
    FromType = ToType.getUnqualifiedType();
1905
2.36M
  } else 
if (1.75M
S.IsBlockPointerConversion(FromType, ToType, FromType)1.75M
) {
1906
8
    SCS.Second = ICK_Block_Pointer_Conversion;
1907
1.75M
  } else if (AllowObjCWritebackConversion &&
1908
1.75M
             
S.isObjCWritebackConversion(FromType, ToType, FromType)409
) {
1909
19
    SCS.Second = ICK_Writeback_Conversion;
1910
1.75M
  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1911
1.75M
                                   FromType, IncompatibleObjC)) {
1912
    // Pointer conversions (C++ 4.10).
1913
147k
    SCS.Second = ICK_Pointer_Conversion;
1914
147k
    SCS.IncompatibleObjC = IncompatibleObjC;
1915
147k
    FromType = FromType.getUnqualifiedType();
1916
1.60M
  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1917
1.60M
                                         InOverloadResolution, FromType)) {
1918
    // Pointer to member conversions (4.11).
1919
1.22k
    SCS.Second = ICK_Pointer_Member;
1920
1.60M
  } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1921
464k
    SCS.Second = SecondICK;
1922
464k
    FromType = ToType.getUnqualifiedType();
1923
1.14M
  } else if (!S.getLangOpts().CPlusPlus &&
1924
1.14M
             
S.Context.typesAreCompatible(ToType, FromType)729k
) {
1925
    // Compatible conversions (Clang extension for C function overloading)
1926
610
    SCS.Second = ICK_Compatible_Conversion;
1927
610
    FromType = ToType.getUnqualifiedType();
1928
1.14M
  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1929
1.14M
                                             InOverloadResolution,
1930
1.14M
                                             SCS, CStyle)) {
1931
1
    SCS.Second = ICK_TransparentUnionConversion;
1932
1
    FromType = ToType;
1933
1.14M
  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1934
1.14M
                                 CStyle)) {
1935
    // tryAtomicConversion has updated the standard conversion sequence
1936
    // appropriately.
1937
636
    return true;
1938
1.14M
  } else if (ToType->isEventT() &&
1939
1.14M
             
From->isIntegerConstantExpr(S.getASTContext())2
&&
1940
1.14M
             
From->EvaluateKnownConstInt(S.getASTContext()) == 02
) {
1941
2
    SCS.Second = ICK_Zero_Event_Conversion;
1942
2
    FromType = ToType;
1943
1.14M
  } else if (ToType->isQueueT() &&
1944
1.14M
             
From->isIntegerConstantExpr(S.getASTContext())4
&&
1945
1.14M
             
(From->EvaluateKnownConstInt(S.getASTContext()) == 0)4
) {
1946
2
    SCS.Second = ICK_Zero_Queue_Conversion;
1947
2
    FromType = ToType;
1948
1.14M
  } else if (ToType->isSamplerT() &&
1949
1.14M
             
From->isIntegerConstantExpr(S.getASTContext())1
) {
1950
1
    SCS.Second = ICK_Compatible_Conversion;
1951
1
    FromType = ToType;
1952
1.14M
  } else {
1953
    // No second conversion required.
1954
1.14M
    SCS.Second = ICK_Identity;
1955
1.14M
  }
1956
22.8M
  SCS.setToType(1, FromType);
1957
1958
  // The third conversion can be a function pointer conversion or a
1959
  // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1960
22.8M
  bool ObjCLifetimeConversion;
1961
22.8M
  if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1962
    // Function pointer conversions (removing 'noexcept') including removal of
1963
    // 'noreturn' (Clang extension).
1964
154
    SCS.Third = ICK_Function_Conversion;
1965
22.8M
  } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1966
22.8M
                                         ObjCLifetimeConversion)) {
1967
56.9k
    SCS.Third = ICK_Qualification;
1968
56.9k
    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1969
56.9k
    FromType = ToType;
1970
22.7M
  } else {
1971
    // No conversion required
1972
22.7M
    SCS.Third = ICK_Identity;
1973
22.7M
  }
1974
1975
  // C++ [over.best.ics]p6:
1976
  //   [...] Any difference in top-level cv-qualification is
1977
  //   subsumed by the initialization itself and does not constitute
1978
  //   a conversion. [...]
1979
22.8M
  QualType CanonFrom = S.Context.getCanonicalType(FromType);
1980
22.8M
  QualType CanonTo = S.Context.getCanonicalType(ToType);
1981
22.8M
  if (CanonFrom.getLocalUnqualifiedType()
1982
22.8M
                                     == CanonTo.getLocalUnqualifiedType() &&
1983
22.8M
      
CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()21.7M
) {
1984
550k
    FromType = ToType;
1985
550k
    CanonFrom = CanonTo;
1986
550k
  }
1987
1988
22.8M
  SCS.setToType(2, FromType);
1989
1990
22.8M
  if (CanonFrom == CanonTo)
1991
21.7M
    return true;
1992
1993
  // If we have not converted the argument type to the parameter type,
1994
  // this is a bad conversion sequence, unless we're resolving an overload in C.
1995
1.09M
  if (S.getLangOpts().CPlusPlus || 
!InOverloadResolution727k
)
1996
369k
    return false;
1997
1998
727k
  ExprResult ER = ExprResult{From};
1999
727k
  Sema::AssignConvertType Conv =
2000
727k
      S.CheckSingleAssignmentConstraints(ToType, ER,
2001
727k
                                         /*Diagnose=*/false,
2002
727k
                                         /*DiagnoseCFAudited=*/false,
2003
727k
                                         /*ConvertRHS=*/false);
2004
727k
  ImplicitConversionKind SecondConv;
2005
727k
  switch (Conv) {
2006
122
  case Sema::Compatible:
2007
122
    SecondConv = ICK_C_Only_Conversion;
2008
122
    break;
2009
  // For our purposes, discarding qualifiers is just as bad as using an
2010
  // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2011
  // qualifiers, as well.
2012
4
  case Sema::CompatiblePointerDiscardsQualifiers:
2013
101k
  case Sema::IncompatiblePointer:
2014
104k
  case Sema::IncompatiblePointerSign:
2015
104k
    SecondConv = ICK_Incompatible_Pointer_Conversion;
2016
104k
    break;
2017
623k
  default:
2018
623k
    return false;
2019
727k
  }
2020
2021
  // First can only be an lvalue conversion, so we pretend that this was the
2022
  // second conversion. First should already be valid from earlier in the
2023
  // function.
2024
104k
  SCS.Second = SecondConv;
2025
104k
  SCS.setToType(1, ToType);
2026
2027
  // Third is Identity, because Second should rank us worse than any other
2028
  // conversion. This could also be ICK_Qualification, but it's simpler to just
2029
  // lump everything in with the second conversion, and we don't gain anything
2030
  // from making this ICK_Qualification.
2031
104k
  SCS.Third = ICK_Identity;
2032
104k
  SCS.setToType(2, ToType);
2033
104k
  return true;
2034
727k
}
2035
2036
static bool
2037
IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2038
                                     QualType &ToType,
2039
                                     bool InOverloadResolution,
2040
                                     StandardConversionSequence &SCS,
2041
1.14M
                                     bool CStyle) {
2042
2043
1.14M
  const RecordType *UT = ToType->getAsUnionType();
2044
1.14M
  if (!UT || 
!UT->getDecl()->hasAttr<TransparentUnionAttr>()1
)
2045
1.14M
    return false;
2046
  // The field to initialize within the transparent union.
2047
1
  RecordDecl *UD = UT->getDecl();
2048
  // It's compatible if the expression matches any of the fields.
2049
1
  for (const auto *it : UD->fields()) {
2050
1
    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2051
1
                             CStyle, /*AllowObjCWritebackConversion=*/false)) {
2052
1
      ToType = it->getType();
2053
1
      return true;
2054
1
    }
2055
1
  }
2056
0
  return false;
2057
1
}
2058
2059
/// IsIntegralPromotion - Determines whether the conversion from the
2060
/// expression From (whose potentially-adjusted type is FromType) to
2061
/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2062
/// sets PromotedType to the promoted type.
2063
12.1M
bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2064
12.1M
  const BuiltinType *To = ToType->getAs<BuiltinType>();
2065
  // All integers are built-in.
2066
12.1M
  if (!To) {
2067
1.42M
    return false;
2068
1.42M
  }
2069
2070
  // An rvalue of type char, signed char, unsigned char, short int, or
2071
  // unsigned short int can be converted to an rvalue of type int if
2072
  // int can represent all the values of the source type; otherwise,
2073
  // the source rvalue can be converted to an rvalue of type unsigned
2074
  // int (C++ 4.5p1).
2075
10.7M
  if (FromType->isPromotableIntegerType() && 
!FromType->isBooleanType()7.85M
&&
2076
10.7M
      
!FromType->isEnumeralType()7.82M
) {
2077
140k
    if (// We can promote any signed, promotable integer type to an int
2078
140k
        (FromType->isSignedIntegerType() ||
2079
         // We can promote any unsigned integer type whose size is
2080
         // less than int to an int.
2081
140k
         
Context.getTypeSize(FromType) < Context.getTypeSize(ToType)76.9k
)) {
2082
130k
      return To->getKind() == BuiltinType::Int;
2083
130k
    }
2084
2085
10.2k
    return To->getKind() == BuiltinType::UInt;
2086
140k
  }
2087
2088
  // C++11 [conv.prom]p3:
2089
  //   A prvalue of an unscoped enumeration type whose underlying type is not
2090
  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2091
  //   following types that can represent all the values of the enumeration
2092
  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2093
  //   unsigned int, long int, unsigned long int, long long int, or unsigned
2094
  //   long long int. If none of the types in that list can represent all the
2095
  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2096
  //   type can be converted to an rvalue a prvalue of the extended integer type
2097
  //   with lowest integer conversion rank (4.13) greater than the rank of long
2098
  //   long in which all the values of the enumeration can be represented. If
2099
  //   there are two such extended types, the signed one is chosen.
2100
  // C++11 [conv.prom]p4:
2101
  //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2102
  //   can be converted to a prvalue of its underlying type. Moreover, if
2103
  //   integral promotion can be applied to its underlying type, a prvalue of an
2104
  //   unscoped enumeration type whose underlying type is fixed can also be
2105
  //   converted to a prvalue of the promoted underlying type.
2106
10.5M
  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2107
    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2108
    // provided for a scoped enumeration.
2109
7.78M
    if (FromEnumType->getDecl()->isScoped())
2110
105k
      return false;
2111
2112
    // We can perform an integral promotion to the underlying type of the enum,
2113
    // even if that's not the promoted type. Note that the check for promoting
2114
    // the underlying type is based on the type alone, and does not consider
2115
    // the bitfield-ness of the actual source expression.
2116
7.68M
    if (FromEnumType->getDecl()->isFixed()) {
2117
169k
      QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2118
169k
      return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2119
169k
             
IsIntegralPromotion(nullptr, Underlying, ToType)153k
;
2120
169k
    }
2121
2122
    // We have already pre-calculated the promotion type, so this is trivial.
2123
7.51M
    if (ToType->isIntegerType() &&
2124
7.51M
        
isCompleteType(From->getBeginLoc(), FromType)5.57M
)
2125
5.57M
      return Context.hasSameUnqualifiedType(
2126
5.57M
          ToType, FromEnumType->getDecl()->getPromotionType());
2127
2128
    // C++ [conv.prom]p5:
2129
    //   If the bit-field has an enumerated type, it is treated as any other
2130
    //   value of that type for promotion purposes.
2131
    //
2132
    // ... so do not fall through into the bit-field checks below in C++.
2133
1.93M
    if (getLangOpts().CPlusPlus)
2134
1.93M
      return false;
2135
1.93M
  }
2136
2137
  // C++0x [conv.prom]p2:
2138
  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2139
  //   to an rvalue a prvalue of the first of the following types that can
2140
  //   represent all the values of its underlying type: int, unsigned int,
2141
  //   long int, unsigned long int, long long int, or unsigned long long int.
2142
  //   If none of the types in that list can represent all the values of its
2143
  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2144
  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2145
  //   type.
2146
2.77M
  if (FromType->isAnyCharacterType() && 
!FromType->isCharType()0
&&
2147
2.77M
      
ToType->isIntegerType()0
) {
2148
    // Determine whether the type we're converting from is signed or
2149
    // unsigned.
2150
0
    bool FromIsSigned = FromType->isSignedIntegerType();
2151
0
    uint64_t FromSize = Context.getTypeSize(FromType);
2152
2153
    // The types we'll try to promote to, in the appropriate
2154
    // order. Try each of these types.
2155
0
    QualType PromoteTypes[6] = {
2156
0
      Context.IntTy, Context.UnsignedIntTy,
2157
0
      Context.LongTy, Context.UnsignedLongTy ,
2158
0
      Context.LongLongTy, Context.UnsignedLongLongTy
2159
0
    };
2160
0
    for (int Idx = 0; Idx < 6; ++Idx) {
2161
0
      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2162
0
      if (FromSize < ToSize ||
2163
0
          (FromSize == ToSize &&
2164
0
           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2165
        // We found the type that we can promote to. If this is the
2166
        // type we wanted, we have a promotion. Otherwise, no
2167
        // promotion.
2168
0
        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2169
0
      }
2170
0
    }
2171
0
  }
2172
2173
  // An rvalue for an integral bit-field (9.6) can be converted to an
2174
  // rvalue of type int if int can represent all the values of the
2175
  // bit-field; otherwise, it can be converted to unsigned int if
2176
  // unsigned int can represent all the values of the bit-field. If
2177
  // the bit-field is larger yet, no integral promotion applies to
2178
  // it. If the bit-field has an enumerated type, it is treated as any
2179
  // other value of that type for promotion purposes (C++ 4.5p3).
2180
  // FIXME: We should delay checking of bit-fields until we actually perform the
2181
  // conversion.
2182
  //
2183
  // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2184
  // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2185
  // bit-fields and those whose underlying type is larger than int) for GCC
2186
  // compatibility.
2187
2.77M
  if (From) {
2188
2.66M
    if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2189
2.44k
      Optional<llvm::APSInt> BitWidth;
2190
2.44k
      if (FromType->isIntegralType(Context) &&
2191
2.44k
          (BitWidth =
2192
2.44k
               MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2193
2.44k
        llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2194
2.44k
        ToSize = Context.getTypeSize(ToType);
2195
2196
        // Are we promoting to an int from a bitfield that fits in an int?
2197
2.44k
        if (*BitWidth < ToSize ||
2198
2.44k
            
(2
FromType->isSignedIntegerType()2
&&
*BitWidth <= ToSize0
)) {
2199
2.43k
          return To->getKind() == BuiltinType::Int;
2200
2.43k
        }
2201
2202
        // Are we promoting to an unsigned int from an unsigned bitfield
2203
        // that fits into an unsigned int?
2204
2
        if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2205
2
          return To->getKind() == BuiltinType::UInt;
2206
2
        }
2207
2208
0
        return false;
2209
2
      }
2210
2.44k
    }
2211
2.66M
  }
2212
2213
  // An rvalue of type bool can be converted to an rvalue of type int,
2214
  // with false becoming zero and true becoming one (C++ 4.5p4).
2215
2.77M
  if (FromType->isBooleanType() && 
To->getKind() == BuiltinType::Int34.0k
) {
2216
13.1k
    return true;
2217
13.1k
  }
2218
2219
2.76M
  return false;
2220
2.77M
}
2221
2222
/// IsFloatingPointPromotion - Determines whether the conversion from
2223
/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2224
/// returns true and sets PromotedType to the promoted type.
2225
11.2M
bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2226
11.2M
  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2227
2.76M
    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2228
      /// An rvalue of type float can be converted to an rvalue of type
2229
      /// double. (C++ 4.6p1).
2230
2.62M
      if (FromBuiltin->getKind() == BuiltinType::Float &&
2231
2.62M
          
ToBuiltin->getKind() == BuiltinType::Double40.7k
)
2232
5.59k
        return true;
2233
2234
      // C99 6.3.1.5p1:
2235
      //   When a float is promoted to double or long double, or a
2236
      //   double is promoted to long double [...].
2237
2.61M
      if (!getLangOpts().CPlusPlus &&
2238
2.61M
          
(154k
FromBuiltin->getKind() == BuiltinType::Float154k
||
2239
154k
           
FromBuiltin->getKind() == BuiltinType::Double149k
) &&
2240
2.61M
          
(10.2k
ToBuiltin->getKind() == BuiltinType::LongDouble10.2k
||
2241
10.2k
           
ToBuiltin->getKind() == BuiltinType::Float12810.1k
||
2242
10.2k
           
ToBuiltin->getKind() == BuiltinType::Ibm12810.1k
))
2243
94
        return true;
2244
2245
      // Half can be promoted to float.
2246
2.61M
      if (!getLangOpts().NativeHalfType &&
2247
2.61M
           
FromBuiltin->getKind() == BuiltinType::Half2.55M
&&
2248
2.61M
          
ToBuiltin->getKind() == BuiltinType::Float254
)
2249
17
        return true;
2250
2.61M
    }
2251
2252
11.2M
  return false;
2253
11.2M
}
2254
2255
/// Determine if a conversion is a complex promotion.
2256
///
2257
/// A complex promotion is defined as a complex -> complex conversion
2258
/// where the conversion between the underlying real types is a
2259
/// floating-point or integral promotion.
2260
11.2M
bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2261
11.2M
  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2262
11.2M
  if (!FromComplex)
2263
11.2M
    return false;
2264
2265
751
  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2266
751
  if (!ToComplex)
2267
626
    return false;
2268
2269
125
  return IsFloatingPointPromotion(FromComplex->getElementType(),
2270
125
                                  ToComplex->getElementType()) ||
2271
125
    IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2272
98
                        ToComplex->getElementType());
2273
751
}
2274
2275
/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2276
/// the pointer type FromPtr to a pointer to type ToPointee, with the
2277
/// same type qualifiers as FromPtr has on its pointee type. ToType,
2278
/// if non-empty, will be a pointer to ToType that may or may not have
2279
/// the right set of qualifiers on its pointee.
2280
///
2281
static QualType
2282
BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2283
                                   QualType ToPointee, QualType ToType,
2284
                                   ASTContext &Context,
2285
92.5k
                                   bool StripObjCLifetime = false) {
2286
92.5k
  assert((FromPtr->getTypeClass() == Type::Pointer ||
2287
92.5k
          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2288
92.5k
         "Invalid similarly-qualified pointer type");
2289
2290
  /// Conversions to 'id' subsume cv-qualifier conversions.
2291
92.5k
  if (ToType->isObjCIdType() || 
ToType->isObjCQualifiedIdType()89.4k
)
2292
3.79k
    return ToType.getUnqualifiedType();
2293
2294
88.7k
  QualType CanonFromPointee
2295
88.7k
    = Context.getCanonicalType(FromPtr->getPointeeType());
2296
88.7k
  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2297
88.7k
  Qualifiers Quals = CanonFromPointee.getQualifiers();
2298
2299
88.7k
  if (StripObjCLifetime)
2300
69.5k
    Quals.removeObjCLifetime();
2301
2302
  // Exact qualifier match -> return the pointer type we're converting to.
2303
88.7k
  if (CanonToPointee.getLocalQualifiers() == Quals) {
2304
    // ToType is exactly what we need. Return it.
2305
75.6k
    if (!ToType.isNull())
2306
75.6k
      return ToType.getUnqualifiedType();
2307
2308
    // Build a pointer to ToPointee. It has the right qualifiers
2309
    // already.
2310
0
    if (isa<ObjCObjectPointerType>(ToType))
2311
0
      return Context.getObjCObjectPointerType(ToPointee);
2312
0
    return Context.getPointerType(ToPointee);
2313
0
  }
2314
2315
  // Just build a canonical type that has the right qualifiers.
2316
13.0k
  QualType QualifiedCanonToPointee
2317
13.0k
    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2318
2319
13.0k
  if (isa<ObjCObjectPointerType>(ToType))
2320
19
    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2321
13.0k
  return Context.getPointerType(QualifiedCanonToPointee);
2322
13.0k
}
2323
2324
static bool isNullPointerConstantForConversion(Expr *Expr,
2325
                                               bool InOverloadResolution,
2326
474k
                                               ASTContext &Context) {
2327
  // Handle value-dependent integral null pointer constants correctly.
2328
  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2329
474k
  if (Expr->isValueDependent() && 
!Expr->isTypeDependent()3.14k
&&
2330
474k
      
Expr->getType()->isIntegerType()3.14k
&&
!Expr->getType()->isEnumeralType()26
)
2331
26
    return !InOverloadResolution;
2332
2333
474k
  return Expr->isNullPointerConstant(Context,
2334
474k
                    InOverloadResolution? 
Expr::NPC_ValueDependentIsNotNull272k
2335
474k
                                        : 
Expr::NPC_ValueDependentIsNull201k
);
2336
474k
}
2337
2338
/// IsPointerConversion - Determines whether the conversion of the
2339
/// expression From, which has the (possibly adjusted) type FromType,
2340
/// can be converted to the type ToType via a pointer conversion (C++
2341
/// 4.10). If so, returns true and places the converted type (that
2342
/// might differ from ToType in its cv-qualifiers at some level) into
2343
/// ConvertedType.
2344
///
2345
/// This routine also supports conversions to and from block pointers
2346
/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2347
/// pointers to interfaces. FIXME: Once we've determined the
2348
/// appropriate overloading rules for Objective-C, we may want to
2349
/// split the Objective-C checks into a different routine; however,
2350
/// GCC seems to consider all of these conversions to be pointer
2351
/// conversions, so for now they live here. IncompatibleObjC will be
2352
/// set if the conversion is an allowed Objective-C conversion that
2353
/// should result in a warning.
2354
bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2355
                               bool InOverloadResolution,
2356
                               QualType& ConvertedType,
2357
1.75M
                               bool &IncompatibleObjC) {
2358
1.75M
  IncompatibleObjC = false;
2359
1.75M
  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2360
1.75M
                              IncompatibleObjC))
2361
4.17k
    return true;
2362
2363
  // Conversion from a null pointer constant to any Objective-C pointer type.
2364
1.75M
  if (ToType->isObjCObjectPointerType() &&
2365
1.75M
      
isNullPointerConstantForConversion(From, InOverloadResolution, Context)7.26k
) {
2366
1.53k
    ConvertedType = ToType;
2367
1.53k
    return true;
2368
1.53k
  }
2369
2370
  // Blocks: Block pointers can be converted to void*.
2371
1.75M
  if (FromType->isBlockPointerType() && 
ToType->isPointerType()63
&&
2372
1.75M
      
ToType->castAs<PointerType>()->getPointeeType()->isVoidType()50
) {
2373
18
    ConvertedType = ToType;
2374
18
    return true;
2375
18
  }
2376
  // Blocks: A null pointer constant can be converted to a block
2377
  // pointer type.
2378
1.75M
  if (ToType->isBlockPointerType() &&
2379
1.75M
      
isNullPointerConstantForConversion(From, InOverloadResolution, Context)61
) {
2380
12
    ConvertedType = ToType;
2381
12
    return true;
2382
12
  }
2383
2384
  // If the left-hand-side is nullptr_t, the right side can be a null
2385
  // pointer constant.
2386
1.75M
  if (ToType->isNullPtrType() &&
2387
1.75M
      
isNullPointerConstantForConversion(From, InOverloadResolution, Context)2.72k
) {
2388
24
    ConvertedType = ToType;
2389
24
    return true;
2390
24
  }
2391
2392
1.75M
  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2393
1.75M
  if (!ToTypePtr)
2394
1.28M
    return false;
2395
2396
  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2397
464k
  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2398
53.1k
    ConvertedType = ToType;
2399
53.1k
    return true;
2400
53.1k
  }
2401
2402
  // Beyond this point, both types need to be pointers
2403
  // , including objective-c pointers.
2404
410k
  QualType ToPointeeType = ToTypePtr->getPointeeType();
2405
410k
  if (FromType->isObjCObjectPointerType() && 
ToPointeeType->isVoidType()5.10k
&&
2406
410k
      
!getLangOpts().ObjCAutoRefCount4.95k
) {
2407
4.94k
    ConvertedType = BuildSimilarlyQualifiedPointerType(
2408
4.94k
        FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2409
4.94k
        Context);
2410
4.94k
    return true;
2411
4.94k
  }
2412
405k
  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2413
405k
  if (!FromTypePtr)
2414
8.23k
    return false;
2415
2416
397k
  QualType FromPointeeType = FromTypePtr->getPointeeType();
2417
2418
  // If the unqualified pointee types are the same, this can't be a
2419
  // pointer conversion, so don't do all of the work below.
2420
397k
  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2421
47.0k
    return false;
2422
2423
  // An rvalue of type "pointer to cv T," where T is an object type,
2424
  // can be converted to an rvalue of type "pointer to cv void" (C++
2425
  // 4.10p2).
2426
350k
  if (FromPointeeType->isIncompleteOrObjectType() &&
2427
350k
      
ToPointeeType->isVoidType()348k
) {
2428
69.5k
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2429
69.5k
                                                       ToPointeeType,
2430
69.5k
                                                       ToType, Context,
2431
69.5k
                                                   /*StripObjCLifetime=*/true);
2432
69.5k
    return true;
2433
69.5k
  }
2434
2435
  // MSVC allows implicit function to void* type conversion.
2436
281k
  if (getLangOpts().MSVCCompat && 
FromPointeeType->isFunctionType()992
&&
2437
281k
      
ToPointeeType->isVoidType()76
) {
2438
15
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2439
15
                                                       ToPointeeType,
2440
15
                                                       ToType, Context);
2441
15
    return true;
2442
15
  }
2443
2444
  // When we're overloading in C, we allow a special kind of pointer
2445
  // conversion for compatible-but-not-identical pointee types.
2446
281k
  if (!getLangOpts().CPlusPlus &&
2447
281k
      
Context.typesAreCompatible(FromPointeeType, ToPointeeType)144k
) {
2448
241
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2449
241
                                                       ToPointeeType,
2450
241
                                                       ToType, Context);
2451
241
    return true;
2452
241
  }
2453
2454
  // C++ [conv.ptr]p3:
2455
  //
2456
  //   An rvalue of type "pointer to cv D," where D is a class type,
2457
  //   can be converted to an rvalue of type "pointer to cv B," where
2458
  //   B is a base class (clause 10) of D. If B is an inaccessible
2459
  //   (clause 11) or ambiguous (10.2) base class of D, a program that
2460
  //   necessitates this conversion is ill-formed. The result of the
2461
  //   conversion is a pointer to the base class sub-object of the
2462
  //   derived class object. The null pointer value is converted to
2463
  //   the null pointer value of the destination type.
2464
  //
2465
  // Note that we do not check for ambiguity or inaccessibility
2466
  // here. That is handled by CheckPointerConversion.
2467
280k
  if (getLangOpts().CPlusPlus && 
FromPointeeType->isRecordType()136k
&&
2468
280k
      
ToPointeeType->isRecordType()27.6k
&&
2469
280k
      
!Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)18.8k
&&
2470
280k
      
IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)18.8k
) {
2471
13.5k
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2472
13.5k
                                                       ToPointeeType,
2473
13.5k
                                                       ToType, Context);
2474
13.5k
    return true;
2475
13.5k
  }
2476
2477
267k
  if (FromPointeeType->isVectorType() && 
ToPointeeType->isVectorType()132k
&&
2478
267k
      
Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)96.8k
) {
2479
2
    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2480
2
                                                       ToPointeeType,
2481
2
                                                       ToType, Context);
2482
2
    return true;
2483
2
  }
2484
2485
267k
  return false;
2486
267k
}
2487
2488
/// Adopt the given qualifiers for the given type.
2489
4.23k
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2490
4.23k
  Qualifiers TQs = T.getQualifiers();
2491
2492
  // Check whether qualifiers already match.
2493
4.23k
  if (TQs == Qs)
2494
4.21k
    return T;
2495
2496
22
  if (Qs.compatiblyIncludes(TQs))
2497
4
    return Context.getQualifiedType(T, Qs);
2498
2499
18
  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2500
22
}
2501
2502
/// isObjCPointerConversion - Determines whether this is an
2503
/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2504
/// with the same arguments and return values.
2505
bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2506
                                   QualType& ConvertedType,
2507
1.75M
                                   bool &IncompatibleObjC) {
2508
1.75M
  if (!getLangOpts().ObjC)
2509
1.65M
    return false;
2510
2511
  // The set of qualifiers on the type we're converting from.
2512
98.0k
  Qualifiers FromQualifiers = FromType.getQualifiers();
2513
2514
  // First, we handle all conversions on ObjC object pointer types.
2515
98.0k
  const ObjCObjectPointerType* ToObjCPtr =
2516
98.0k
    ToType->getAs<ObjCObjectPointerType>();
2517
98.0k
  const ObjCObjectPointerType *FromObjCPtr =
2518
98.0k
    FromType->getAs<ObjCObjectPointerType>();
2519
2520
98.0k
  if (ToObjCPtr && 
FromObjCPtr11.5k
) {
2521
    // If the pointee types are the same (ignoring qualifications),
2522
    // then this is not a pointer conversion.
2523
4.40k
    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2524
4.40k
                                       FromObjCPtr->getPointeeType()))
2525
117
      return false;
2526
2527
    // Conversion between Objective-C pointers.
2528
4.28k
    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2529
4.14k
      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2530
4.14k
      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2531
4.14k
      if (getLangOpts().CPlusPlus && 
LHS1.33k
&&
RHS334
&&
2532
4.14k
          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2533
93
                                                FromObjCPtr->getPointeeType()))
2534
1
        return false;
2535
4.14k
      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2536
4.14k
                                                   ToObjCPtr->getPointeeType(),
2537
4.14k
                                                         ToType, Context);
2538
4.14k
      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2539
4.14k
      return true;
2540
4.14k
    }
2541
2542
139
    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2543
      // Okay: this is some kind of implicit downcast of Objective-C
2544
      // interfaces, which is permitted. However, we're going to
2545
      // complain about it.
2546
28
      IncompatibleObjC = true;
2547
28
      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2548
28
                                                   ToObjCPtr->getPointeeType(),
2549
28
                                                         ToType, Context);
2550
28
      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2551
28
      return true;
2552
28
    }
2553
139
  }
2554
  // Beyond this point, both types need to be C pointers or block pointers.
2555
93.7k
  QualType ToPointeeType;
2556
93.7k
  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2557
57.4k
    ToPointeeType = ToCPtr->getPointeeType();
2558
36.3k
  else if (const BlockPointerType *ToBlockPtr =
2559
36.3k
            ToType->getAs<BlockPointerType>()) {
2560
    // Objective C++: We're able to convert from a pointer to any object
2561
    // to a block pointer type.
2562
61
    if (FromObjCPtr && 
FromObjCPtr->isObjCBuiltinType()23
) {
2563
16
      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2564
16
      return true;
2565
16
    }
2566
45
    ToPointeeType = ToBlockPtr->getPointeeType();
2567
45
  }
2568
36.2k
  else if (FromType->getAs<BlockPointerType>() &&
2569
36.2k
           
ToObjCPtr32
&&
ToObjCPtr->isObjCBuiltinType()32
) {
2570
    // Objective C++: We're able to convert from a block pointer type to a
2571
    // pointer to any object.
2572
31
    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2573
31
    return true;
2574
31
  }
2575
36.2k
  else
2576
36.2k
    return false;
2577
2578
57.5k
  QualType FromPointeeType;
2579
57.5k
  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2580
45.7k
    FromPointeeType = FromCPtr->getPointeeType();
2581
11.7k
  else if (const BlockPointerType *FromBlockPtr =
2582
11.7k
           FromType->getAs<BlockPointerType>())
2583
48
    FromPointeeType = FromBlockPtr->getPointeeType();
2584
11.6k
  else
2585
11.6k
    return false;
2586
2587
  // If we have pointers to pointers, recursively check whether this
2588
  // is an Objective-C conversion.
2589
45.8k
  if (FromPointeeType->isPointerType() && 
ToPointeeType->isPointerType()176
&&
2590
45.8k
      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2591
13
                              IncompatibleObjC)) {
2592
    // We always complain about this conversion.
2593
0
    IncompatibleObjC = true;
2594
0
    ConvertedType = Context.getPointerType(ConvertedType);
2595
0
    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2596
0
    return true;
2597
0
  }
2598
  // Allow conversion of pointee being objective-c pointer to another one;
2599
  // as in I* to id.
2600
45.8k
  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2601
45.8k
      
ToPointeeType->getAs<ObjCObjectPointerType>()2.57k
&&
2602
45.8k
      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2603
101
                              IncompatibleObjC)) {
2604
2605
16
    ConvertedType = Context.getPointerType(ConvertedType);
2606
16
    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2607
16
    return true;
2608
16
  }
2609
2610
  // If we have pointers to functions or blocks, check whether the only
2611
  // differences in the argument and result types are in Objective-C
2612
  // pointer conversions. If so, we permit the conversion (but
2613
  // complain about it).
2614
45.7k
  const FunctionProtoType *FromFunctionType
2615
45.7k
    = FromPointeeType->getAs<FunctionProtoType>();
2616
45.7k
  const FunctionProtoType *ToFunctionType
2617
45.7k
    = ToPointeeType->getAs<FunctionProtoType>();
2618
45.7k
  if (FromFunctionType && 
ToFunctionType78
) {
2619
    // If the function types are exactly the same, this isn't an
2620
    // Objective-C pointer conversion.
2621
68
    if (Context.getCanonicalType(FromPointeeType)
2622
68
          == Context.getCanonicalType(ToPointeeType))
2623
45
      return false;
2624
2625
    // Perform the quick checks that will tell us whether these
2626
    // function types are obviously different.
2627
23
    if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2628
23
        
FromFunctionType->isVariadic() != ToFunctionType->isVariadic()18
||
2629
23
        
FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()18
)
2630
5
      return false;
2631
2632
18
    bool HasObjCConversion = false;
2633
18
    if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2634
18
        Context.getCanonicalType(ToFunctionType->getReturnType())) {
2635
      // Okay, the types match exactly. Nothing to do.
2636
15
    } else 
if (3
isObjCPointerConversion(FromFunctionType->getReturnType(),
2637
3
                                       ToFunctionType->getReturnType(),
2638
3
                                       ConvertedType, IncompatibleObjC)) {
2639
      // Okay, we have an Objective-C pointer conversion.
2640
2
      HasObjCConversion = true;
2641
2
    } else {
2642
      // Function types are too different. Abort.
2643
1
      return false;
2644
1
    }
2645
2646
    // Check argument types.
2647
17
    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2648
37
         ArgIdx != NumArgs; 
++ArgIdx20
) {
2649
20
      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2650
20
      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2651
20
      if (Context.getCanonicalType(FromArgType)
2652
20
            == Context.getCanonicalType(ToArgType)) {
2653
        // Okay, the types match exactly. Nothing to do.
2654
19
      } else 
if (1
isObjCPointerConversion(FromArgType, ToArgType,
2655
1
                                         ConvertedType, IncompatibleObjC)) {
2656
        // Okay, we have an Objective-C pointer conversion.
2657
1
        HasObjCConversion = true;
2658
1
      } else {
2659
        // Argument types are too different. Abort.
2660
0
        return false;
2661
0
      }
2662
20
    }
2663
2664
17
    if (HasObjCConversion) {
2665
      // We had an Objective-C conversion. Allow this pointer
2666
      // conversion, but complain about it.
2667
3
      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2668
3
      IncompatibleObjC = true;
2669
3
      return true;
2670
3
    }
2671
17
  }
2672
2673
45.7k
  return false;
2674
45.7k
}
2675
2676
/// Determine whether this is an Objective-C writeback conversion,
2677
/// used for parameter passing when performing automatic reference counting.
2678
///
2679
/// \param FromType The type we're converting form.
2680
///
2681
/// \param ToType The type we're converting to.
2682
///
2683
/// \param ConvertedType The type that will be produced after applying
2684
/// this conversion.
2685
bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2686
3.70k
                                     QualType &ConvertedType) {
2687
3.70k
  if (!getLangOpts().ObjCAutoRefCount ||
2688
3.70k
      Context.hasSameUnqualifiedType(FromType, ToType))
2689
2.63k
    return false;
2690
2691
  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2692
1.07k
  QualType ToPointee;
2693
1.07k
  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2694
513
    ToPointee = ToPointer->getPointeeType();
2695
558
  else
2696
558
    return false;
2697
2698
513
  Qualifiers ToQuals = ToPointee.getQualifiers();
2699
513
  if (!ToPointee->isObjCLifetimeType() ||
2700
513
      
ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing136
||
2701
513
      
!ToQuals.withoutObjCLifetime().empty()98
)
2702
426
    return false;
2703
2704
  // Argument must be a pointer to __strong to __weak.
2705
87
  QualType FromPointee;
2706
87
  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2707
86
    FromPointee = FromPointer->getPointeeType();
2708
1
  else
2709
1
    return false;
2710
2711
86
  Qualifiers FromQuals = FromPointee.getQualifiers();
2712
86
  if (!FromPointee->isObjCLifetimeType() ||
2713
86
      
(85
FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong85
&&
2714
85
       
FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak20
))
2715
6
    return false;
2716
2717
  // Make sure that we have compatible qualifiers.
2718
80
  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2719
80
  if (!ToQuals.compatiblyIncludes(FromQuals))
2720
0
    return false;
2721
2722
  // Remove qualifiers from the pointee type we're converting from; they
2723
  // aren't used in the compatibility check belong, and we'll be adding back
2724
  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2725
80
  FromPointee = FromPointee.getUnqualifiedType();
2726
2727
  // The unqualified form of the pointee types must be compatible.
2728
80
  ToPointee = ToPointee.getUnqualifiedType();
2729
80
  bool IncompatibleObjC;
2730
80
  if (Context.typesAreCompatible(FromPointee, ToPointee))
2731
77
    FromPointee = ToPointee;
2732
3
  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2733
3
                                    IncompatibleObjC))
2734
0
    return false;
2735
2736
  /// Construct the type we're converting to, which is a pointer to
2737
  /// __autoreleasing pointee.
2738
80
  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2739
80
  ConvertedType = Context.getPointerType(FromPointee);
2740
80
  return true;
2741
80
}
2742
2743
bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2744
1.75M
                                    QualType& ConvertedType) {
2745
1.75M
  QualType ToPointeeType;
2746
1.75M
  if (const BlockPointerType *ToBlockPtr =
2747
1.75M
        ToType->getAs<BlockPointerType>())
2748
85
    ToPointeeType = ToBlockPtr->getPointeeType();
2749
1.75M
  else
2750
1.75M
    return false;
2751
2752
85
  QualType FromPointeeType;
2753
85
  if (const BlockPointerType *FromBlockPtr =
2754
85
      FromType->getAs<BlockPointerType>())
2755
21
    FromPointeeType = FromBlockPtr->getPointeeType();
2756
64
  else
2757
64
    return false;
2758
  // We have pointer to blocks, check whether the only
2759
  // differences in the argument and result types are in Objective-C
2760
  // pointer conversions. If so, we permit the conversion.
2761
2762
21
  const FunctionProtoType *FromFunctionType
2763
21
    = FromPointeeType->getAs<FunctionProtoType>();
2764
21
  const FunctionProtoType *ToFunctionType
2765
21
    = ToPointeeType->getAs<FunctionProtoType>();
2766
2767
21
  if (!FromFunctionType || !ToFunctionType)
2768
0
    return false;
2769
2770
21
  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2771
0
    return true;
2772
2773
  // Perform the quick checks that will tell us whether these
2774
  // function types are obviously different.
2775
21
  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2776
21
      
FromFunctionType->isVariadic() != ToFunctionType->isVariadic()17
)
2777
4
    return false;
2778
2779
17
  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2780
17
  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2781
17
  if (FromEInfo != ToEInfo)
2782
0
    return false;
2783
2784
17
  bool IncompatibleObjC = false;
2785
17
  if (Context.hasSameType(FromFunctionType->getReturnType(),
2786
17
                          ToFunctionType->getReturnType())) {
2787
    // Okay, the types match exactly. Nothing to do.
2788
11
  } else {
2789
6
    QualType RHS = FromFunctionType->getReturnType();
2790
6
    QualType LHS = ToFunctionType->getReturnType();
2791
6
    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2792
6
        !RHS.hasQualifiers() && 
LHS.hasQualifiers()5
)
2793
1
       LHS = LHS.getUnqualifiedType();
2794
2795
6
     if (Context.hasSameType(RHS,LHS)) {
2796
       // OK exact match.
2797
5
     } else if (isObjCPointerConversion(RHS, LHS,
2798
5
                                        ConvertedType, IncompatibleObjC)) {
2799
4
     if (IncompatibleObjC)
2800
0
       return false;
2801
     // Okay, we have an Objective-C pointer conversion.
2802
4
     }
2803
1
     else
2804
1
       return false;
2805
6
   }
2806
2807
   // Check argument types.
2808
16
   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2809
32
        ArgIdx != NumArgs; 
++ArgIdx16
) {
2810
18
     IncompatibleObjC = false;
2811
18
     QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2812
18
     QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2813
18
     if (Context.hasSameType(FromArgType, ToArgType)) {
2814
       // Okay, the types match exactly. Nothing to do.
2815
13
     } else 
if (5
isObjCPointerConversion(ToArgType, FromArgType,
2816
5
                                        ConvertedType, IncompatibleObjC)) {
2817
4
       if (IncompatibleObjC)
2818
1
         return false;
2819
       // Okay, we have an Objective-C pointer conversion.
2820
4
     } else
2821
       // Argument types are too different. Abort.
2822
1
       return false;
2823
18
   }
2824
2825
14
   SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2826
14
   bool CanUseToFPT, CanUseFromFPT;
2827
14
   if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2828
14
                                      CanUseToFPT, CanUseFromFPT,
2829
14
                                      NewParamInfos))
2830
6
     return false;
2831
2832
8
   ConvertedType = ToType;
2833
8
   return true;
2834
14
}
2835
2836
enum {
2837
  ft_default,
2838
  ft_different_class,
2839
  ft_parameter_arity,
2840
  ft_parameter_mismatch,
2841
  ft_return_type,
2842
  ft_qualifer_mismatch,
2843
  ft_noexcept
2844
};
2845
2846
/// Attempts to get the FunctionProtoType from a Type. Handles
2847
/// MemberFunctionPointers properly.
2848
12.0k
static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2849
12.0k
  if (auto *FPT = FromType->getAs<FunctionProtoType>())
2850
413
    return FPT;
2851
2852
11.6k
  if (auto *MPT = FromType->getAs<MemberPointerType>())
2853
3
    return MPT->getPointeeType()->getAs<FunctionProtoType>();
2854
2855
11.5k
  return nullptr;
2856
11.6k
}
2857
2858
/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2859
/// function types.  Catches different number of parameter, mismatch in
2860
/// parameter types, and different return types.
2861
void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2862
7.37k
                                      QualType FromType, QualType ToType) {
2863
  // If either type is not valid, include no extra info.
2864
7.37k
  if (FromType.isNull() || ToType.isNull()) {
2865
1.21k
    PDiag << ft_default;
2866
1.21k
    return;
2867
1.21k
  }
2868
2869
  // Get the function type from the pointers.
2870
6.16k
  if (FromType->isMemberPointerType() && 
ToType->isMemberPointerType()44
) {
2871
44
    const auto *FromMember = FromType->castAs<MemberPointerType>(),
2872
44
               *ToMember = ToType->castAs<MemberPointerType>();
2873
44
    if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2874
6
      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2875
6
            << QualType(FromMember->getClass(), 0);
2876
6
      return;
2877
6
    }
2878
38
    FromType = FromMember->getPointeeType();
2879
38
    ToType = ToMember->getPointeeType();
2880
38
  }
2881
2882
6.15k
  if (FromType->isPointerType())
2883
372
    FromType = FromType->getPointeeType();
2884
6.15k
  if (ToType->isPointerType())
2885
571
    ToType = ToType->getPointeeType();
2886
2887
  // Remove references.
2888
6.15k
  FromType = FromType.getNonReferenceType();
2889
6.15k
  ToType = ToType.getNonReferenceType();
2890
2891
  // Don't print extra info for non-specialized template functions.
2892
6.15k
  if (FromType->isInstantiationDependentType() &&
2893
6.15k
      
!FromType->getAs<TemplateSpecializationType>()10
) {
2894
10
    PDiag << ft_default;
2895
10
    return;
2896
10
  }
2897
2898
  // No extra info for same types.
2899
6.14k
  if (Context.hasSameType(FromType, ToType)) {
2900
139
    PDiag << ft_default;
2901
139
    return;
2902
139
  }
2903
2904
6.00k
  const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2905
6.00k
                          *ToFunction = tryGetFunctionProtoType(ToType);
2906
2907
  // Both types need to be function types.
2908
6.00k
  if (!FromFunction || 
!ToFunction210
) {
2909
5.83k
    PDiag << ft_default;
2910
5.83k
    return;
2911
5.83k
  }
2912
2913
176
  if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2914
54
    PDiag << ft_parameter_arity << ToFunction->getNumParams()
2915
54
          << FromFunction->getNumParams();
2916
54
    return;
2917
54
  }
2918
2919
  // Handle different parameter types.
2920
122
  unsigned ArgPos;
2921
122
  if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2922
48
    PDiag << ft_parameter_mismatch << ArgPos + 1
2923
48
          << ToFunction->getParamType(ArgPos)
2924
48
          << FromFunction->getParamType(ArgPos);
2925
48
    return;
2926
48
  }
2927
2928
  // Handle different return type.
2929
74
  if (!Context.hasSameType(FromFunction->getReturnType(),
2930
74
                           ToFunction->getReturnType())) {
2931
12
    PDiag << ft_return_type << ToFunction->getReturnType()
2932
12
          << FromFunction->getReturnType();
2933
12
    return;
2934
12
  }
2935
2936
62
  if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2937
30
    PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2938
30
          << FromFunction->getMethodQuals();
2939
30
    return;
2940
30
  }
2941
2942
  // Handle exception specification differences on canonical type (in C++17
2943
  // onwards).
2944
32
  if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2945
32
          ->isNothrow() !=
2946
32
      cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2947
32
          ->isNothrow()) {
2948
17
    PDiag << ft_noexcept;
2949
17
    return;
2950
17
  }
2951
2952
  // Unable to find a difference, so add no extra info.
2953
15
  PDiag << ft_default;
2954
15
}
2955
2956
/// FunctionParamTypesAreEqual - This routine checks two function proto types
2957
/// for equality of their argument types. Caller has already checked that
2958
/// they have same number of arguments.  If the parameters are different,
2959
/// ArgPos will have the parameter index of the first different parameter.
2960
bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2961
                                      const FunctionProtoType *NewType,
2962
64.4M
                                      unsigned *ArgPos) {
2963
64.4M
  for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2964
64.4M
                                              N = NewType->param_type_begin(),
2965
64.4M
                                              E = OldType->param_type_end();
2966
114M
       O && (O != E); 
++O, ++N49.6M
) {
2967
    // Ignore address spaces in pointee type. This is to disallow overloading
2968
    // on __ptr32/__ptr64 address spaces.
2969
113M
    QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2970
113M
    QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2971
2972
113M
    if (!Context.hasSameType(Old, New)) {
2973
64.3M
      if (ArgPos)
2974
48
        *ArgPos = O - OldType->param_type_begin();
2975
64.3M
      return false;
2976
64.3M
    }
2977
113M
  }
2978
136k
  return true;
2979
64.4M
}
2980
2981
/// CheckPointerConversion - Check the pointer conversion from the
2982
/// expression From to the type ToType. This routine checks for
2983
/// ambiguous or inaccessible derived-to-base pointer
2984
/// conversions for which IsPointerConversion has already returned
2985
/// true. It returns true and produces a diagnostic if there was an
2986
/// error, or returns false otherwise.
2987
bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2988
                                  CastKind &Kind,
2989
                                  CXXCastPath& BasePath,
2990
                                  bool IgnoreBaseAccess,
2991
108k
                                  bool Diagnose) {
2992
108k
  QualType FromType = From->getType();
2993
108k
  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2994
2995
108k
  Kind = CK_BitCast;
2996
2997
108k
  if (Diagnose && !IsCStyleOrFunctionalCast && 
!FromType->isAnyPointerType()99.9k
&&
2998
108k
      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2999
43.8k
          Expr::NPCK_ZeroExpression) {
3000
27
    if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3001
9
      DiagRuntimeBehavior(From->getExprLoc(), From,
3002
9
                          PDiag(diag::warn_impcast_bool_to_null_pointer)
3003
9
                            << ToType << From->getSourceRange());
3004
18
    else if (!isUnevaluatedContext())
3005
18
      Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3006
18
        << ToType << From->getSourceRange();
3007
27
  }
3008
108k
  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3009
103k
    if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3010
53.4k
      QualType FromPointeeType = FromPtrType->getPointeeType(),
3011
53.4k
               ToPointeeType   = ToPtrType->getPointeeType();
3012
3013
53.4k
      if (FromPointeeType->isRecordType() && 
ToPointeeType->isRecordType()20.1k
&&
3014
53.4k
          
!Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)5.60k
) {
3015
        // We must have a derived-to-base conversion. Check an
3016
        // ambiguous or inaccessible conversion.
3017
5.60k
        unsigned InaccessibleID = 0;
3018
5.60k
        unsigned AmbiguousID = 0;
3019
5.60k
        if (Diagnose) {
3020
5.60k
          InaccessibleID = diag::err_upcast_to_inaccessible_base;
3021
5.60k
          AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3022
5.60k
        }
3023
5.60k
        if (CheckDerivedToBaseConversion(
3024
5.60k
                FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3025
5.60k
                From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3026
5.60k
                &BasePath, IgnoreBaseAccess))
3027
13
          return true;
3028
3029
        // The conversion was successful.
3030
5.59k
        Kind = CK_DerivedToBase;
3031
5.59k
      }
3032
3033
53.4k
      if (Diagnose && !IsCStyleOrFunctionalCast &&
3034
53.4k
          
FromPointeeType->isFunctionType()49.6k
&&
ToPointeeType->isVoidType()17
) {
3035
15
        assert(getLangOpts().MSVCCompat &&
3036
15
               "this should only be possible with MSVCCompat!");
3037
0
        Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3038
15
            << From->getSourceRange();
3039
15
      }
3040
53.4k
    }
3041
103k
  } else 
if (const ObjCObjectPointerType *4.59k
ToPtrType4.59k
=
3042
4.59k
               ToType->getAs<ObjCObjectPointerType>()) {
3043
4.45k
    if (const ObjCObjectPointerType *FromPtrType =
3044
4.45k
          FromType->getAs<ObjCObjectPointerType>()) {
3045
      // Objective-C++ conversions are always okay.
3046
      // FIXME: We should have a different class of conversions for the
3047
      // Objective-C++ implicit conversions.
3048
1.28k
      if (FromPtrType->isObjCBuiltinType() || 
ToPtrType->isObjCBuiltinType()1.00k
)
3049
1.10k
        return false;
3050
3.16k
    } else if (FromType->isBlockPointerType()) {
3051
28
      Kind = CK_BlockPointerToObjCPointerCast;
3052
3.13k
    } else {
3053
3.13k
      Kind = CK_CPointerToObjCPointerCast;
3054
3.13k
    }
3055
4.45k
  } else 
if (148
ToType->isBlockPointerType()148
) {
3056
128
    if (!FromType->isBlockPointerType())
3057
128
      Kind = CK_AnyPointerToBlockPointerCast;
3058
128
  }
3059
3060
  // We shouldn't fall into this case unless it's valid for other
3061
  // reasons.
3062
107k
  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3063
49.9k
    Kind = CK_NullToPointer;
3064
3065
107k
  return false;
3066
108k
}
3067
3068
/// IsMemberPointerConversion - Determines whether the conversion of the
3069
/// expression From, which has the (possibly adjusted) type FromType, can be
3070
/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3071
/// If so, returns true and places the converted type (that might differ from
3072
/// ToType in its cv-qualifiers at some level) into ConvertedType.
3073
bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3074
                                     QualType ToType,
3075
                                     bool InOverloadResolution,
3076
1.60M
                                     QualType &ConvertedType) {
3077
1.60M
  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3078
1.60M
  if (!ToTypePtr)
3079
1.60M
    return false;
3080
3081
  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3082
1.87k
  if (From->isNullPointerConstant(Context,
3083
1.87k
                    InOverloadResolution? 
Expr::NPC_ValueDependentIsNotNull426
3084
1.87k
                                        : 
Expr::NPC_ValueDependentIsNull1.44k
)) {
3085
725
    ConvertedType = ToType;
3086
725
    return true;
3087
725
  }
3088
3089
  // Otherwise, both types have to be member pointers.
3090
1.14k
  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3091
1.14k
  if (!FromTypePtr)
3092
9
    return false;
3093
3094
  // A pointer to member of B can be converted to a pointer to member of D,
3095
  // where D is derived from B (C++ 4.11p2).
3096
1.14k
  QualType FromClass(FromTypePtr->getClass(), 0);
3097
1.14k
  QualType ToClass(ToTypePtr->getClass(), 0);
3098
3099
1.14k
  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3100
1.14k
      
IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)659
) {
3101
499
    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3102
499
                                                 ToClass.getTypePtr());
3103
499
    return true;
3104
499
  }
3105
3106
641
  return false;
3107
1.14k
}
3108
3109
/// CheckMemberPointerConversion - Check the member pointer conversion from the
3110
/// expression From to the type ToType. This routine checks for ambiguous or
3111
/// virtual or inaccessible base-to-derived member pointer conversions
3112
/// for which IsMemberPointerConversion has already returned true. It returns
3113
/// true and produces a diagnostic if there was an error, or returns false
3114
/// otherwise.
3115
bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3116
                                        CastKind &Kind,
3117
                                        CXXCastPath &BasePath,
3118
684
                                        bool IgnoreBaseAccess) {
3119
684
  QualType FromType = From->getType();
3120
684
  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3121
684
  if (!FromPtrType) {
3122
    // This must be a null pointer to member pointer conversion
3123
270
    assert(From->isNullPointerConstant(Context,
3124
270
                                       Expr::NPC_ValueDependentIsNull) &&
3125
270
           "Expr must be null pointer constant!");
3126
0
    Kind = CK_NullToMemberPointer;
3127
270
    return false;
3128
270
  }
3129
3130
414
  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3131
414
  assert(ToPtrType && "No member pointer cast has a target type "
3132
414
                      "that is not a member pointer.");
3133
3134
0
  QualType FromClass = QualType(FromPtrType->getClass(), 0);
3135
414
  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3136
3137
  // FIXME: What about dependent types?
3138
414
  assert(FromClass->isRecordType() && "Pointer into non-class.");
3139
0
  assert(ToClass->isRecordType() && "Pointer into non-class.");
3140
3141
0
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3142
414
                     /*DetectVirtual=*/true);
3143
414
  bool DerivationOkay =
3144
414
      IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3145
414
  assert(DerivationOkay &&
3146
414
         "Should not have been called if derivation isn't OK.");
3147
0
  (void)DerivationOkay;
3148
3149
414
  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3150
414
                                  getUnqualifiedType())) {
3151
7
    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3152
7
    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3153
7
      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3154
7
    return true;
3155
7
  }
3156
3157
407
  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3158
17
    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3159
17
      << FromClass << ToClass << QualType(VBase, 0)
3160
17
      << From->getSourceRange();
3161
17
    return true;
3162
17
  }
3163
3164
390
  if (!IgnoreBaseAccess)
3165
335
    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3166
335
                         Paths.front(),
3167
335
                         diag::err_downcast_from_inaccessible_base);
3168
3169
  // Must be a base to derived member conversion.
3170
390
  BuildBasePathArray(Paths, BasePath);
3171
390
  Kind = CK_BaseToDerivedMemberPointer;
3172
390
  return false;
3173
407
}
3174
3175
/// Determine whether the lifetime conversion between the two given
3176
/// qualifiers sets is nontrivial.
3177
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3178
98
                                               Qualifiers ToQuals) {
3179
  // Converting anything to const __unsafe_unretained is trivial.
3180
98
  if (ToQuals.hasConst() &&
3181
98
      
ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone68
)
3182
13
    return false;
3183
3184
85
  return true;
3185
98
}
3186
3187
/// Perform a single iteration of the loop for checking if a qualification
3188
/// conversion is valid.
3189
///
3190
/// Specifically, check whether any change between the qualifiers of \p
3191
/// FromType and \p ToType is permissible, given knowledge about whether every
3192
/// outer layer is const-qualified.
3193
static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3194
                                          bool CStyle, bool IsTopLevel,
3195
                                          bool &PreviousToQualsIncludeConst,
3196
5.47M
                                          bool &ObjCLifetimeConversion) {
3197
5.47M
  Qualifiers FromQuals = FromType.getQualifiers();
3198
5.47M
  Qualifiers ToQuals = ToType.getQualifiers();
3199
3200
  // Ignore __unaligned qualifier if this type is void.
3201
5.47M
  if (ToType.getUnqualifiedType()->isVoidType())
3202
13.4k
    FromQuals.removeUnaligned();
3203
3204
  // Objective-C ARC:
3205
  //   Check Objective-C lifetime conversions.
3206
5.47M
  if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3207
191
    if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3208
98
      if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3209
85
        ObjCLifetimeConversion = true;
3210
98
      FromQuals.removeObjCLifetime();
3211
98
      ToQuals.removeObjCLifetime();
3212
98
    } else {
3213
      // Qualification conversions cannot cast between different
3214
      // Objective-C lifetime qualifiers.
3215
93
      return false;
3216
93
    }
3217
191
  }
3218
3219
  // Allow addition/removal of GC attributes but not changing GC attributes.
3220
5.47M
  if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3221
5.47M
      
(8
!FromQuals.hasObjCGCAttr()8
||
!ToQuals.hasObjCGCAttr()2
)) {
3222
6
    FromQuals.removeObjCGCAttr();
3223
6
    ToQuals.removeObjCGCAttr();
3224
6
  }
3225
3226
  //   -- for every j > 0, if const is in cv 1,j then const is in cv
3227
  //      2,j, and similarly for volatile.
3228
5.47M
  if (!CStyle && 
!ToQuals.compatiblyIncludes(FromQuals)5.42M
)
3229
136k
    return false;
3230
3231
  // If address spaces mismatch:
3232
  //  - in top level it is only valid to convert to addr space that is a
3233
  //    superset in all cases apart from C-style casts where we allow
3234
  //    conversions between overlapping address spaces.
3235
  //  - in non-top levels it is not a valid conversion.
3236
5.33M
  if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3237
5.33M
      
(2.06k
!IsTopLevel2.06k
||
3238
2.06k
       
!(2.03k
ToQuals.isAddressSpaceSupersetOf(FromQuals)2.03k
||
3239
2.03k
         
(95
CStyle95
&&
FromQuals.isAddressSpaceSupersetOf(ToQuals)95
))))
3240
129
    return false;
3241
3242
  //   -- if the cv 1,j and cv 2,j are different, then const is in
3243
  //      every cv for 0 < k < j.
3244
5.33M
  if (!CStyle && 
FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()5.28M
&&
3245
5.33M
      
!PreviousToQualsIncludeConst2.37M
)
3246
719
    return false;
3247
3248
  // The following wording is from C++20, where the result of the conversion
3249
  // is T3, not T2.
3250
  //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3251
  //      "array of unknown bound of"
3252
5.33M
  if (FromType->isIncompleteArrayType() && 
!ToType->isIncompleteArrayType()7
)
3253
0
    return false;
3254
3255
  //   -- if the resulting P3,i is different from P1,i [...], then const is
3256
  //      added to every cv 3_k for 0 < k < i.
3257
5.33M
  if (!CStyle && 
FromType->isConstantArrayType()5.28M
&&
3258
5.33M
      
ToType->isIncompleteArrayType()9.30k
&&
!PreviousToQualsIncludeConst44
)
3259
2
    return false;
3260
3261
  // Keep track of whether all prior cv-qualifiers in the "to" type
3262
  // include const.
3263
5.33M
  PreviousToQualsIncludeConst =
3264
5.33M
      PreviousToQualsIncludeConst && 
ToQuals.hasConst()5.33M
;
3265
5.33M
  return true;
3266
5.33M
}
3267
3268
/// IsQualificationConversion - Determines whether the conversion from
3269
/// an rvalue of type FromType to ToType is a qualification conversion
3270
/// (C++ 4.4).
3271
///
3272
/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3273
/// when the qualification conversion involves a change in the Objective-C
3274
/// object lifetime.
3275
bool
3276
Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3277
22.8M
                                bool CStyle, bool &ObjCLifetimeConversion) {
3278
22.8M
  FromType = Context.getCanonicalType(FromType);
3279
22.8M
  ToType = Context.getCanonicalType(ToType);
3280
22.8M
  ObjCLifetimeConversion = false;
3281
3282
  // If FromType and ToType are the same type, this is not a
3283
  // qualification conversion.
3284
22.8M
  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3285
21.6M
    return false;
3286
3287
  // (C++ 4.4p4):
3288
  //   A conversion can add cv-qualifiers at levels other than the first
3289
  //   in multi-level pointers, subject to the following rules: [...]
3290
1.17M
  bool PreviousToQualsIncludeConst = true;
3291
1.17M
  bool UnwrappedAnyPointer = false;
3292
1.46M
  while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3293
337k
    if (!isQualificationConversionStep(
3294
337k
            FromType, ToType, CStyle, !UnwrappedAnyPointer,
3295
337k
            PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3296
46.0k
      return false;
3297
291k
    UnwrappedAnyPointer = true;
3298
291k
  }
3299
3300
  // We are left with FromType and ToType being the pointee types
3301
  // after unwrapping the original FromType and ToType the same number
3302
  // of times. If we unwrapped any pointers, and if FromType and
3303
  // ToType have the same unqualified type (since we checked
3304
  // qualifiers above), then this is a qualification conversion.
3305
1.12M
  return UnwrappedAnyPointer && 
Context.hasSameUnqualifiedType(FromType,ToType)290k
;
3306
1.17M
}
3307
3308
/// - Determine whether this is a conversion from a scalar type to an
3309
/// atomic type.
3310
///
3311
/// If successful, updates \c SCS's second and third steps in the conversion
3312
/// sequence to finish the conversion.
3313
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3314
                                bool InOverloadResolution,
3315
                                StandardConversionSequence &SCS,
3316
1.14M
                                bool CStyle) {
3317
1.14M
  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3318
1.14M
  if (!ToAtomic)
3319
1.14M
    return false;
3320
3321
690
  StandardConversionSequence InnerSCS;
3322
690
  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3323
690
                            InOverloadResolution, InnerSCS,
3324
690
                            CStyle, /*AllowObjCWritebackConversion=*/false))
3325
54
    return false;
3326
3327
636
  SCS.Second = InnerSCS.Second;
3328
636
  SCS.setToType(1, InnerSCS.getToType(1));
3329
636
  SCS.Third = InnerSCS.Third;
3330
636
  SCS.QualificationIncludesObjCLifetime
3331
636
    = InnerSCS.QualificationIncludesObjCLifetime;
3332
636
  SCS.setToType(2, InnerSCS.getToType(2));
3333
636
  return true;
3334
690
}
3335
3336
static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3337
                                              CXXConstructorDecl *Constructor,
3338
183
                                              QualType Type) {
3339
183
  const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3340
183
  if (CtorType->getNumParams() > 0) {
3341
171
    QualType FirstArg = CtorType->getParamType(0);
3342
171
    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3343
90
      return true;
3344
171
  }
3345
93
  return false;
3346
183
}
3347
3348
static OverloadingResult
3349
IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3350
                                       CXXRecordDecl *To,
3351
                                       UserDefinedConversionSequence &User,
3352
                                       OverloadCandidateSet &CandidateSet,
3353
853
                                       bool AllowExplicit) {
3354
853
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3355
3.96k
  for (auto *D : S.LookupConstructors(To)) {
3356
3.96k
    auto Info = getConstructorInfo(D);
3357
3.96k
    if (!Info)
3358
8
      continue;
3359
3360
3.96k
    bool Usable = !Info.Constructor->isInvalidDecl() &&
3361
3.96k
                  S.isInitListConstructor(Info.Constructor);
3362
3.96k
    if (Usable) {
3363
125
      bool SuppressUserConversions = false;
3364
125
      if (Info.ConstructorTmpl)
3365
0
        S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3366
0
                                       /*ExplicitArgs*/ nullptr, From,
3367
0
                                       CandidateSet, SuppressUserConversions,
3368
0
                                       /*PartialOverloading*/ false,
3369
0
                                       AllowExplicit);
3370
125
      else
3371
125
        S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3372
125
                               CandidateSet, SuppressUserConversions,
3373
125
                               /*PartialOverloading*/ false, AllowExplicit);
3374
125
    }
3375
3.96k
  }
3376
3377
853
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3378
3379
853
  OverloadCandidateSet::iterator Best;
3380
853
  switch (auto Result =
3381
853
              CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3382
2
  case OR_Deleted:
3383
122
  case OR_Success: {
3384
    // Record the standard conversion we used and the conversion function.
3385
122
    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3386
122
    QualType ThisType = Constructor->getThisType();
3387
    // Initializer lists don't have conversions as such.
3388
122
    User.Before.setAsIdentityConversion();
3389
122
    User.HadMultipleCandidates = HadMultipleCandidates;
3390
122
    User.ConversionFunction = Constructor;
3391
122
    User.FoundConversionFunction = Best->FoundDecl;
3392
122
    User.After.setAsIdentityConversion();
3393
122
    User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3394
122
    User.After.setAllToTypes(ToType);
3395
122
    return Result;
3396
2
  }
3397
3398
731
  case OR_No_Viable_Function:
3399
731
    return OR_No_Viable_Function;
3400
0
  case OR_Ambiguous:
3401
0
    return OR_Ambiguous;
3402
853
  }
3403
3404
0
  llvm_unreachable("Invalid OverloadResult!");
3405
0
}
3406
3407
/// Determines whether there is a user-defined conversion sequence
3408
/// (C++ [over.ics.user]) that converts expression From to the type
3409
/// ToType. If such a conversion exists, User will contain the
3410
/// user-defined conversion sequence that performs such a conversion
3411
/// and this routine will return true. Otherwise, this routine returns
3412
/// false and User is unspecified.
3413
///
3414
/// \param AllowExplicit  true if the conversion should consider C++0x
3415
/// "explicit" conversion functions as well as non-explicit conversion
3416
/// functions (C++0x [class.conv.fct]p2).
3417
///
3418
/// \param AllowObjCConversionOnExplicit true if the conversion should
3419
/// allow an extra Objective-C pointer conversion on uses of explicit
3420
/// constructors. Requires \c AllowExplicit to also be set.
3421
static OverloadingResult
3422
IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3423
                        UserDefinedConversionSequence &User,
3424
                        OverloadCandidateSet &CandidateSet,
3425
                        AllowedExplicit AllowExplicit,
3426
1.19M
                        bool AllowObjCConversionOnExplicit) {
3427
1.19M
  assert(AllowExplicit != AllowedExplicit::None ||
3428
1.19M
         !AllowObjCConversionOnExplicit);
3429
0
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3430
3431
  // Whether we will only visit constructors.
3432
1.19M
  bool ConstructorsOnly = false;
3433
3434
  // If the type we are conversion to is a class type, enumerate its
3435
  // constructors.
3436
1.19M
  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3437
    // C++ [over.match.ctor]p1:
3438
    //   When objects of class type are direct-initialized (8.5), or
3439
    //   copy-initialized from an expression of the same or a
3440
    //   derived class type (8.5), overload resolution selects the
3441
    //   constructor. [...] For copy-initialization, the candidate
3442
    //   functions are all the converting constructors (12.3.1) of
3443
    //   that class. The argument list is the expression-list within
3444
    //   the parentheses of the initializer.
3445
169k
    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3446
169k
        (From->getType()->getAs<RecordType>() &&
3447
169k
         
S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)76.1k
))
3448
0
      ConstructorsOnly = true;
3449
3450
169k
    if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3451
      // We're not going to find any constructors.
3452
159k
    } else if (CXXRecordDecl *ToRecordDecl
3453
159k
                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3454
3455
159k
      Expr **Args = &From;
3456
159k
      unsigned NumArgs = 1;
3457
159k
      bool ListInitializing = false;
3458
159k
      if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3459
        // But first, see if there is an init-list-constructor that will work.
3460
853
        OverloadingResult Result = IsInitializerListConstructorConversion(
3461
853
            S, From, ToType, ToRecordDecl, User, CandidateSet,
3462
853
            AllowExplicit == AllowedExplicit::All);
3463
853
        if (Result != OR_No_Viable_Function)
3464
122
          return Result;
3465
        // Never mind.
3466
731
        CandidateSet.clear(
3467
731
            OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3468
3469
        // If we're list-initializing, we pass the individual elements as
3470
        // arguments, not the entire list.
3471
731
        Args = InitList->getInits();
3472
731
        NumArgs = InitList->getNumInits();
3473
731
        ListInitializing = true;
3474
731
      }
3475
3476
753k
      
for (auto *D : S.LookupConstructors(ToRecordDecl))158k
{
3477
753k
        auto Info = getConstructorInfo(D);
3478
753k
        if (!Info)
3479
488
          continue;
3480
3481
753k
        bool Usable = !Info.Constructor->isInvalidDecl();
3482
753k
        if (!ListInitializing)
3483
750k
          Usable = Usable && Info.Constructor->isConvertingConstructor(
3484
750k
                                 /*AllowExplicit*/ true);
3485
753k
        if (Usable) {
3486
496k
          bool SuppressUserConversions = !ConstructorsOnly;
3487
          // C++20 [over.best.ics.general]/4.5:
3488
          //   if the target is the first parameter of a constructor [of class
3489
          //   X] and the constructor [...] is a candidate by [...] the second
3490
          //   phase of [over.match.list] when the initializer list has exactly
3491
          //   one element that is itself an initializer list, [...] and the
3492
          //   conversion is to X or reference to cv X, user-defined conversion
3493
          //   sequences are not cnosidered.
3494
496k
          if (SuppressUserConversions && ListInitializing) {
3495
2.92k
            SuppressUserConversions =
3496
2.92k
                NumArgs == 1 && 
isa<InitListExpr>(Args[0])1.03k
&&
3497
2.92k
                isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3498
183
                                                  ToType);
3499
2.92k
          }
3500
496k
          if (Info.ConstructorTmpl)
3501
103k
            S.AddTemplateOverloadCandidate(
3502
103k
                Info.ConstructorTmpl, Info.FoundDecl,
3503
103k
                /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3504
103k
                CandidateSet, SuppressUserConversions,
3505
103k
                /*PartialOverloading*/ false,
3506
103k
                AllowExplicit == AllowedExplicit::All);
3507
393k
          else
3508
            // Allow one user-defined conversion when user specifies a
3509
            // From->ToType conversion via an static cast (c-style, etc).
3510
393k
            S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3511
393k
                                   llvm::makeArrayRef(Args, NumArgs),
3512
393k
                                   CandidateSet, SuppressUserConversions,
3513
393k
                                   /*PartialOverloading*/ false,
3514
393k
                                   AllowExplicit == AllowedExplicit::All);
3515
496k
        }
3516
753k
      }
3517
158k
    }
3518
169k
  }
3519
3520
  // Enumerate conversion functions, if we're allowed to.
3521
1.19M
  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3522
1.19M
  } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3523
    // No conversion functions from incomplete types.
3524
1.18M
  } else if (const RecordType *FromRecordType =
3525
1.18M
                 From->getType()->getAs<RecordType>()) {
3526
834k
    if (CXXRecordDecl *FromRecordDecl
3527
834k
         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3528
      // Add all of the conversion functions as candidates.
3529
834k
      const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3530
1.32M
      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; 
++I489k
) {
3531
489k
        DeclAccessPair FoundDecl = I.getPair();
3532
489k
        NamedDecl *D = FoundDecl.getDecl();
3533
489k
        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3534
489k
        if (isa<UsingShadowDecl>(D))
3535
14
          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3536
3537
489k
        CXXConversionDecl *Conv;
3538
489k
        FunctionTemplateDecl *ConvTemplate;
3539
489k
        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3540
2.89k
          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3541
486k
        else
3542
486k
          Conv = cast<CXXConversionDecl>(D);
3543
3544
489k
        if (ConvTemplate)
3545
2.89k
          S.AddTemplateConversionCandidate(
3546
2.89k
              ConvTemplate, FoundDecl, ActingContext, From, ToType,
3547
2.89k
              CandidateSet, AllowObjCConversionOnExplicit,
3548
2.89k
              AllowExplicit != AllowedExplicit::None);
3549
486k
        else
3550
486k
          S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3551
486k
                                   CandidateSet, AllowObjCConversionOnExplicit,
3552
486k
                                   AllowExplicit != AllowedExplicit::None);
3553
489k
      }
3554
834k
    }
3555
834k
  }
3556
3557
1.19M
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3558
3559
1.19M
  OverloadCandidateSet::iterator Best;
3560
1.19M
  switch (auto Result =
3561
1.19M
              CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3562
425k
  case OR_Success:
3563
425k
  case OR_Deleted:
3564
    // Record the standard conversion we used and the conversion function.
3565
425k
    if (CXXConstructorDecl *Constructor
3566
425k
          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3567
      // C++ [over.ics.user]p1:
3568
      //   If the user-defined conversion is specified by a
3569
      //   constructor (12.3.1), the initial standard conversion
3570
      //   sequence converts the source type to the type required by
3571
      //   the argument of the constructor.
3572
      //
3573
30.2k
      QualType ThisType = Constructor->getThisType();
3574
30.2k
      if (isa<InitListExpr>(From)) {
3575
        // Initializer lists don't have conversions as such.
3576
589
        User.Before.setAsIdentityConversion();
3577
29.6k
      } else {
3578
29.6k
        if (Best->Conversions[0].isEllipsis())
3579
398
          User.EllipsisConversion = true;
3580
29.2k
        else {
3581
29.2k
          User.Before = Best->Conversions[0].Standard;
3582
29.2k
          User.EllipsisConversion = false;
3583
29.2k
        }
3584
29.6k
      }
3585
30.2k
      User.HadMultipleCandidates = HadMultipleCandidates;
3586
30.2k
      User.ConversionFunction = Constructor;
3587
30.2k
      User.FoundConversionFunction = Best->FoundDecl;
3588
30.2k
      User.After.setAsIdentityConversion();
3589
30.2k
      User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3590
30.2k
      User.After.setAllToTypes(ToType);
3591
30.2k
      return Result;
3592
30.2k
    }
3593
395k
    if (CXXConversionDecl *Conversion
3594
395k
                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3595
      // C++ [over.ics.user]p1:
3596
      //
3597
      //   [...] If the user-defined conversion is specified by a
3598
      //   conversion function (12.3.2), the initial standard
3599
      //   conversion sequence converts the source type to the
3600
      //   implicit object parameter of the conversion function.
3601
395k
      User.Before = Best->Conversions[0].Standard;
3602
395k
      User.HadMultipleCandidates = HadMultipleCandidates;
3603
395k
      User.ConversionFunction = Conversion;
3604
395k
      User.FoundConversionFunction = Best->FoundDecl;
3605
395k
      User.EllipsisConversion = false;
3606
3607
      // C++ [over.ics.user]p2:
3608
      //   The second standard conversion sequence converts the
3609
      //   result of the user-defined conversion to the target type
3610
      //   for the sequence. Since an implicit conversion sequence
3611
      //   is an initialization, the special rules for
3612
      //   initialization by user-defined conversion apply when
3613
      //   selecting the best user-defined conversion for a
3614
      //   user-defined conversion sequence (see 13.3.3 and
3615
      //   13.3.3.1).
3616
395k
      User.After = Best->FinalConversion;
3617
395k
      return Result;
3618
395k
    }
3619
0
    llvm_unreachable("Not a constructor or conversion function?");
3620
3621
757k
  case OR_No_Viable_Function:
3622
757k
    return OR_No_Viable_Function;
3623
3624
7.98k
  case OR_Ambiguous:
3625
7.98k
    return OR_Ambiguous;
3626
1.19M
  }
3627
3628
0
  llvm_unreachable("Invalid OverloadResult!");
3629
0
}
3630
3631
bool
3632
1.23k
Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3633
1.23k
  ImplicitConversionSequence ICS;
3634
1.23k
  OverloadCandidateSet CandidateSet(From->getExprLoc(),
3635
1.23k
                                    OverloadCandidateSet::CSK_Normal);
3636
1.23k
  OverloadingResult OvResult =
3637
1.23k
    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3638
1.23k
                            CandidateSet, AllowedExplicit::None, false);
3639
3640
1.23k
  if (!(OvResult == OR_Ambiguous ||
3641
1.23k
        
(1.23k
OvResult == OR_No_Viable_Function1.23k
&&
!CandidateSet.empty()1.23k
)))
3642
144
    return false;
3643
3644
1.08k
  auto Cands = CandidateSet.CompleteCandidates(
3645
1.08k
      *this,
3646
1.08k
      OvResult == OR_Ambiguous ? 
OCD_AmbiguousCandidates2
:
OCD_AllCandidates1.08k
,
3647
1.08k
      From);
3648
1.08k
  if (OvResult == OR_Ambiguous)
3649
2
    Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3650
2
        << From->getType() << ToType << From->getSourceRange();
3651
1.08k
  else { // OR_No_Viable_Function && !CandidateSet.empty()
3652
1.08k
    if (!RequireCompleteType(From->getBeginLoc(), ToType,
3653
1.08k
                             diag::err_typecheck_nonviable_condition_incomplete,
3654
1.08k
                             From->getType(), From->getSourceRange()))
3655
1.08k
      Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3656
1.08k
          << false << From->getType() << From->getSourceRange() << ToType;
3657
1.08k
  }
3658
3659
1.08k
  CandidateSet.NoteCandidates(
3660
1.08k
                              *this, From, Cands);
3661
1.08k
  return true;
3662
1.23k
}
3663
3664
// Helper for compareConversionFunctions that gets the FunctionType that the
3665
// conversion-operator return  value 'points' to, or nullptr.
3666
static const FunctionType *
3667
168
getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3668
168
  const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3669
168
  const PointerType *RetPtrTy =
3670
168
      ConvFuncTy->getReturnType()->getAs<PointerType>();
3671
3672
168
  if (!RetPtrTy)
3673
0
    return nullptr;
3674
3675
168
  return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3676
168
}
3677
3678
/// Compare the user-defined conversion functions or constructors
3679
/// of two user-defined conversion sequences to determine whether any ordering
3680
/// is possible.
3681
static ImplicitConversionSequence::CompareKind
3682
compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3683
33.0k
                           FunctionDecl *Function2) {
3684
33.0k
  CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3685
33.0k
  CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3686
33.0k
  if (!Conv1 || 
!Conv233.0k
)
3687
30
    return ImplicitConversionSequence::Indistinguishable;
3688
3689
33.0k
  if (!Conv1->getParent()->isLambda() || 
!Conv2->getParent()->isLambda()96
)
3690
32.9k
    return ImplicitConversionSequence::Indistinguishable;
3691
3692
  // Objective-C++:
3693
  //   If both conversion functions are implicitly-declared conversions from
3694
  //   a lambda closure type to a function pointer and a block pointer,
3695
  //   respectively, always prefer the conversion to a function pointer,
3696
  //   because the function pointer is more lightweight and is more likely
3697
  //   to keep code working.
3698
96
  if (S.getLangOpts().ObjC && 
S.getLangOpts().CPlusPlus1112
) {
3699
12
    bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3700
12
    bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3701
12
    if (Block1 != Block2)
3702
12
      return Block1 ? 
ImplicitConversionSequence::Worse4
3703
12
                    : 
ImplicitConversionSequence::Better8
;
3704
12
  }
3705
3706
  // In order to support multiple calling conventions for the lambda conversion
3707
  // operator (such as when the free and member function calling convention is
3708
  // different), prefer the 'free' mechanism, followed by the calling-convention
3709
  // of operator(). The latter is in place to support the MSVC-like solution of
3710
  // defining ALL of the possible conversions in regards to calling-convention.
3711
84
  const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3712
84
  const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3713
3714
84
  if (Conv1FuncRet && Conv2FuncRet &&
3715
84
      Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3716
52
    CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3717
52
    CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3718
3719
52
    CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3720
52
    const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3721
3722
52
    CallingConv CallOpCC =
3723
52
        CallOp->getType()->castAs<FunctionType>()->getCallConv();
3724
52
    CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3725
52
        CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3726
52
    CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3727
52
        CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3728
3729
52
    CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3730
52
    for (CallingConv CC : PrefOrder) {
3731
52
      if (Conv1CC == CC)
3732
26
        return ImplicitConversionSequence::Better;
3733
26
      if (Conv2CC == CC)
3734
26
        return ImplicitConversionSequence::Worse;
3735
26
    }
3736
52
  }
3737
3738
32
  return ImplicitConversionSequence::Indistinguishable;
3739
84
}
3740
3741
static bool hasDeprecatedStringLiteralToCharPtrConversion(
3742
68.5M
    const ImplicitConversionSequence &ICS) {
3743
68.5M
  return (ICS.isStandard() && 
ICS.Standard.DeprecatedStringLiteralToCharPtr66.2M
) ||
3744
68.5M
         
(68.5M
ICS.isUserDefined()68.5M
&&
3745
68.5M
          
ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr2.15M
);
3746
68.5M
}
3747
3748
/// CompareImplicitConversionSequences - Compare two implicit
3749
/// conversion sequences to determine whether one is better than the
3750
/// other or if they are indistinguishable (C++ 13.3.3.2).
3751
static ImplicitConversionSequence::CompareKind
3752
CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3753
                                   const ImplicitConversionSequence& ICS1,
3754
                                   const ImplicitConversionSequence& ICS2)
3755
15.7M
{
3756
  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3757
  // conversion sequences (as defined in 13.3.3.1)
3758
  //   -- a standard conversion sequence (13.3.3.1.1) is a better
3759
  //      conversion sequence than a user-defined conversion sequence or
3760
  //      an ellipsis conversion sequence, and
3761
  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3762
  //      conversion sequence than an ellipsis conversion sequence
3763
  //      (13.3.3.1.3).
3764
  //
3765
  // C++0x [over.best.ics]p10:
3766
  //   For the purpose of ranking implicit conversion sequences as
3767
  //   described in 13.3.3.2, the ambiguous conversion sequence is
3768
  //   treated as a user-defined sequence that is indistinguishable
3769
  //   from any other user-defined conversion sequence.
3770
3771
  // String literal to 'char *' conversion has been deprecated in C++03. It has
3772
  // been removed from C++11. We still accept this conversion, if it happens at
3773
  // the best viable function. Otherwise, this conversion is considered worse
3774
  // than ellipsis conversion. Consider this as an extension; this is not in the
3775
  // standard. For example:
3776
  //
3777
  // int &f(...);    // #1
3778
  // void f(char*);  // #2
3779
  // void g() { int &r = f("foo"); }
3780
  //
3781
  // In C++03, we pick #2 as the best viable function.
3782
  // In C++11, we pick #1 as the best viable function, because ellipsis
3783
  // conversion is better than string-literal to char* conversion (since there
3784
  // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3785
  // convert arguments, #2 would be the best viable function in C++11.
3786
  // If the best viable function has this conversion, a warning will be issued
3787
  // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3788
3789
15.7M
  if (S.getLangOpts().CPlusPlus11 && 
!S.getLangOpts().WritableStrings15.1M
&&
3790
15.7M
      hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3791
15.1M
          hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3792
      // Ill-formedness must not differ
3793
15.7M
      
ICS1.isBad() == ICS2.isBad()8
)
3794
6
    return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3795
6
               ? 
ImplicitConversionSequence::Worse4
3796
6
               : 
ImplicitConversionSequence::Better2
;
3797
3798
15.7M
  if (ICS1.getKindRank() < ICS2.getKindRank())
3799
108k
    return ImplicitConversionSequence::Better;
3800
15.6M
  if (ICS2.getKindRank() < ICS1.getKindRank())
3801
74.3k
    return ImplicitConversionSequence::Worse;
3802
3803
  // The following checks require both conversion sequences to be of
3804
  // the same kind.
3805
15.5M
  if (ICS1.getKind() != ICS2.getKind())
3806
4
    return ImplicitConversionSequence::Indistinguishable;
3807
3808
15.5M
  ImplicitConversionSequence::CompareKind Result =
3809
15.5M
      ImplicitConversionSequence::Indistinguishable;
3810
3811
  // Two implicit conversion sequences of the same form are
3812
  // indistinguishable conversion sequences unless one of the
3813
  // following rules apply: (C++ 13.3.3.2p3):
3814
3815
  // List-initialization sequence L1 is a better conversion sequence than
3816
  // list-initialization sequence L2 if:
3817
  // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3818
  //   if not that,
3819
  // — L1 and L2 convert to arrays of the same element type, and either the
3820
  //   number of elements n_1 initialized by L1 is less than the number of
3821
  //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3822
  //   an array of unknown bound and L1 does not,
3823
  // even if one of the other rules in this paragraph would otherwise apply.
3824
15.5M
  if (!ICS1.isBad()) {
3825
15.5M
    bool StdInit1 = false, StdInit2 = false;
3826
15.5M
    if (ICS1.hasInitializerListContainerType())
3827
337
      StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3828
337
                                        nullptr);
3829
15.5M
    if (ICS2.hasInitializerListContainerType())
3830
204
      StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3831
204
                                        nullptr);
3832
15.5M
    if (StdInit1 != StdInit2)
3833
129
      return StdInit1 ? 
ImplicitConversionSequence::Better87
3834
129
                      : 
ImplicitConversionSequence::Worse42
;
3835
3836
15.5M
    if (ICS1.hasInitializerListContainerType() &&
3837
15.5M
        
ICS2.hasInitializerListContainerType()244
)
3838
150
      if (auto *CAT1 = S.Context.getAsConstantArrayType(
3839
150
              ICS1.getInitializerListContainerType()))
3840
78
        if (auto *CAT2 = S.Context.getAsConstantArrayType(
3841
78
                ICS2.getInitializerListContainerType())) {
3842
78
          if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3843
78
                                               CAT2->getElementType())) {
3844
            // Both to arrays of the same element type
3845
36
            if (CAT1->getSize() != CAT2->getSize())
3846
              // Different sized, the smaller wins
3847
14
              return CAT1->getSize().ult(CAT2->getSize())
3848
14
                         ? ImplicitConversionSequence::Better
3849
14
                         : 
ImplicitConversionSequence::Worse0
;
3850
22
            if (ICS1.isInitializerListOfIncompleteArray() !=
3851
22
                ICS2.isInitializerListOfIncompleteArray())
3852
              // One is incomplete, it loses
3853
6
              return ICS2.isInitializerListOfIncompleteArray()
3854
6
                         ? 
ImplicitConversionSequence::Better3
3855
6
                         : 
ImplicitConversionSequence::Worse3
;
3856
22
          }
3857
78
        }
3858
15.5M
  }
3859
3860
15.5M
  if (ICS1.isStandard())
3861
    // Standard conversion sequence S1 is a better conversion sequence than
3862
    // standard conversion sequence S2 if [...]
3863
14.9M
    Result = CompareStandardConversionSequences(S, Loc,
3864
14.9M
                                                ICS1.Standard, ICS2.Standard);
3865
636k
  else if (ICS1.isUserDefined()) {
3866
    // User-defined conversion sequence U1 is a better conversion
3867
    // sequence than another user-defined conversion sequence U2 if
3868
    // they contain the same user-defined conversion function or
3869
    // constructor and if the second standard conversion sequence of
3870
    // U1 is better than the second standard conversion sequence of
3871
    // U2 (C++ 13.3.3.2p3).
3872
631k
    if (ICS1.UserDefined.ConversionFunction ==
3873
631k
          ICS2.UserDefined.ConversionFunction)
3874
618k
      Result = CompareStandardConversionSequences(S, Loc,
3875
618k
                                                  ICS1.UserDefined.After,
3876
618k
                                                  ICS2.UserDefined.After);
3877
12.4k
    else
3878
12.4k
      Result = compareConversionFunctions(S,
3879
12.4k
                                          ICS1.UserDefined.ConversionFunction,
3880
12.4k
                                          ICS2.UserDefined.ConversionFunction);
3881
631k
  }
3882
3883
15.5M
  return Result;
3884
15.5M
}
3885
3886
// Per 13.3.3.2p3, compare the given standard conversion sequences to
3887
// determine if one is a proper subset of the other.
3888
static ImplicitConversionSequence::CompareKind
3889
compareStandardConversionSubsets(ASTContext &Context,
3890
                                 const StandardConversionSequence& SCS1,
3891
15.5M
                                 const StandardConversionSequence& SCS2) {
3892
15.5M
  ImplicitConversionSequence::CompareKind Result
3893
15.5M
    = ImplicitConversionSequence::Indistinguishable;
3894
3895
  // the identity conversion sequence is considered to be a subsequence of
3896
  // any non-identity conversion sequence
3897
15.5M
  if (SCS1.isIdentityConversion() && 
!SCS2.isIdentityConversion()8.66M
)
3898
7.81M
    return ImplicitConversionSequence::Better;
3899
7.74M
  else if (!SCS1.isIdentityConversion() && 
SCS2.isIdentityConversion()6.89M
)
3900
3.79M
    return ImplicitConversionSequence::Worse;
3901
3902
3.94M
  if (SCS1.Second != SCS2.Second) {
3903
2.32M
    if (SCS1.Second == ICK_Identity)
3904
227
      Result = ImplicitConversionSequence::Better;
3905
2.32M
    else if (SCS2.Second == ICK_Identity)
3906
85
      Result = ImplicitConversionSequence::Worse;
3907
2.31M
    else
3908
2.31M
      return ImplicitConversionSequence::Indistinguishable;
3909
2.32M
  } else 
if (1.62M
!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))1.62M
)
3910
410k
    return ImplicitConversionSequence::Indistinguishable;
3911
3912
1.21M
  if (SCS1.Third == SCS2.Third) {
3913
1.21M
    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? 
Result867k
3914
1.21M
                             : 
ImplicitConversionSequence::Indistinguishable346k
;
3915
1.21M
  }
3916
3917
4.20k
  if (SCS1.Third == ICK_Identity)
3918
2.06k
    return Result == ImplicitConversionSequence::Worse
3919
2.06k
             ? 
ImplicitConversionSequence::Indistinguishable75
3920
2.06k
             : 
ImplicitConversionSequence::Better1.98k
;
3921
3922
2.14k
  if (SCS2.Third == ICK_Identity)
3923
2.14k
    return Result == ImplicitConversionSequence::Better
3924
2.14k
             ? 
ImplicitConversionSequence::Indistinguishable191
3925
2.14k
             : 
ImplicitConversionSequence::Worse1.95k
;
3926
3927
0
  return ImplicitConversionSequence::Indistinguishable;
3928
2.14k
}
3929
3930
/// Determine whether one of the given reference bindings is better
3931
/// than the other based on what kind of bindings they are.
3932
static bool
3933
isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3934
704k
                             const StandardConversionSequence &SCS2) {
3935
  // C++0x [over.ics.rank]p3b4:
3936
  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3937
  //      implicit object parameter of a non-static member function declared
3938
  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3939
  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3940
  //      lvalue reference to a function lvalue and S2 binds an rvalue
3941
  //      reference*.
3942
  //
3943
  // FIXME: Rvalue references. We're going rogue with the above edits,
3944
  // because the semantics in the current C++0x working paper (N3225 at the
3945
  // time of this writing) break the standard definition of std::forward
3946
  // and std::reference_wrapper when dealing with references to functions.
3947
  // Proposed wording changes submitted to CWG for consideration.
3948
704k
  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3949
704k
      
SCS2.BindsImplicitObjectArgumentWithoutRefQualifier411k
)
3950
305k
    return false;
3951
3952
399k
  return (!SCS1.IsLvalueReference && 
SCS1.BindsToRvalue275k
&&
3953
399k
          
SCS2.IsLvalueReference274k
) ||
3954
399k
         
(148k
SCS1.IsLvalueReference148k
&&
SCS1.BindsToFunctionLvalue124k
&&
3955
148k
          
!SCS2.IsLvalueReference1.67k
&&
SCS2.BindsToFunctionLvalue1.60k
);
3956
704k
}
3957
3958
enum class FixedEnumPromotion {
3959
  None,
3960
  ToUnderlyingType,
3961
  ToPromotedUnderlyingType
3962
};
3963
3964
/// Returns kind of fixed enum promotion the \a SCS uses.
3965
static FixedEnumPromotion
3966
3.51M
getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3967
3968
3.51M
  if (SCS.Second != ICK_Integral_Promotion)
3969
3.09M
    return FixedEnumPromotion::None;
3970
3971
425k
  QualType FromType = SCS.getFromType();
3972
425k
  if (!FromType->isEnumeralType())
3973
14.6k
    return FixedEnumPromotion::None;
3974
3975
410k
  EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3976
410k
  if (!Enum->isFixed())
3977
400k
    return FixedEnumPromotion::None;
3978
3979
9.87k
  QualType UnderlyingType = Enum->getIntegerType();
3980
9.87k
  if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3981
9.79k
    return FixedEnumPromotion::ToUnderlyingType;
3982
3983
80
  return FixedEnumPromotion::ToPromotedUnderlyingType;
3984
9.87k
}
3985
3986
/// CompareStandardConversionSequences - Compare two standard
3987
/// conversion sequences to determine whether one is better than the
3988
/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3989
static ImplicitConversionSequence::CompareKind
3990
CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3991
                                   const StandardConversionSequence& SCS1,
3992
                                   const StandardConversionSequence& SCS2)
3993
15.5M
{
3994
  // Standard conversion sequence S1 is a better conversion sequence
3995
  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3996
3997
  //  -- S1 is a proper subsequence of S2 (comparing the conversion
3998
  //     sequences in the canonical form defined by 13.3.3.1.1,
3999
  //     excluding any Lvalue Transformation; the identity conversion
4000
  //     sequence is considered to be a subsequence of any
4001
  //     non-identity conversion sequence) or, if not that,
4002
15.5M
  if (ImplicitConversionSequence::CompareKind CK
4003
15.5M
        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4004
11.6M
    return CK;
4005
4006
  //  -- the rank of S1 is better than the rank of S2 (by the rules
4007
  //     defined below), or, if not that,
4008
3.94M
  ImplicitConversionRank Rank1 = SCS1.getRank();
4009
3.94M
  ImplicitConversionRank Rank2 = SCS2.getRank();
4010
3.94M
  if (Rank1 < Rank2)
4011
1.41M
    return ImplicitConversionSequence::Better;
4012
2.53M
  else if (Rank2 < Rank1)
4013
775k
    return ImplicitConversionSequence::Worse;
4014
4015
  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4016
  // are indistinguishable unless one of the following rules
4017
  // applies:
4018
4019
  //   A conversion that is not a conversion of a pointer, or
4020
  //   pointer to member, to bool is better than another conversion
4021
  //   that is such a conversion.
4022
1.75M
  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4023
112
    return SCS2.isPointerConversionToBool()
4024
112
             ? 
ImplicitConversionSequence::Better105
4025
112
             : 
ImplicitConversionSequence::Worse7
;
4026
4027
  // C++14 [over.ics.rank]p4b2:
4028
  // This is retroactively applied to C++11 by CWG 1601.
4029
  //
4030
  //   A conversion that promotes an enumeration whose underlying type is fixed
4031
  //   to its underlying type is better than one that promotes to the promoted
4032
  //   underlying type, if the two are different.
4033
1.75M
  FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4034
1.75M
  FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4035
1.75M
  if (FEP1 != FixedEnumPromotion::None && 
FEP2 != FixedEnumPromotion::None4.93k
&&
4036
1.75M
      
FEP1 != FEP24.93k
)
4037
20
    return FEP1 == FixedEnumPromotion::ToUnderlyingType
4038
20
               ? ImplicitConversionSequence::Better
4039
20
               : 
ImplicitConversionSequence::Worse0
;
4040
4041
  // C++ [over.ics.rank]p4b2:
4042
  //
4043
  //   If class B is derived directly or indirectly from class A,
4044
  //   conversion of B* to A* is better than conversion of B* to
4045
  //   void*, and conversion of A* to void* is better than conversion
4046
  //   of B* to void*.
4047
1.75M
  bool SCS1ConvertsToVoid
4048
1.75M
    = SCS1.isPointerConversionToVoidPointer(S.Context);
4049
1.75M
  bool SCS2ConvertsToVoid
4050
1.75M
    = SCS2.isPointerConversionToVoidPointer(S.Context);
4051
1.75M
  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4052
    // Exactly one of the conversion sequences is a conversion to
4053
    // a void pointer; it's the worse conversion.
4054
22
    return SCS2ConvertsToVoid ? 
ImplicitConversionSequence::Better19
4055
22
                              : 
ImplicitConversionSequence::Worse3
;
4056
1.75M
  } else if (!SCS1ConvertsToVoid && 
!SCS2ConvertsToVoid1.75M
) {
4057
    // Neither conversion sequence converts to a void pointer; compare
4058
    // their derived-to-base conversions.
4059
1.75M
    if (ImplicitConversionSequence::CompareKind DerivedCK
4060
1.75M
          = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4061
518
      return DerivedCK;
4062
1.75M
  } else 
if (52
SCS1ConvertsToVoid52
&&
SCS2ConvertsToVoid52
&&
4063
52
             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4064
    // Both conversion sequences are conversions to void
4065
    // pointers. Compare the source types to determine if there's an
4066
    // inheritance relationship in their sources.
4067
0
    QualType FromType1 = SCS1.getFromType();
4068
0
    QualType FromType2 = SCS2.getFromType();
4069
4070
    // Adjust the types we're converting from via the array-to-pointer
4071
    // conversion, if we need to.
4072
0
    if (SCS1.First == ICK_Array_To_Pointer)
4073
0
      FromType1 = S.Context.getArrayDecayedType(FromType1);
4074
0
    if (SCS2.First == ICK_Array_To_Pointer)
4075
0
      FromType2 = S.Context.getArrayDecayedType(FromType2);
4076
4077
0
    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4078
0
    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4079
4080
0
    if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4081
0
      return ImplicitConversionSequence::Better;
4082
0
    else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4083
0
      return ImplicitConversionSequence::Worse;
4084
4085
    // Objective-C++: If one interface is more specific than the
4086
    // other, it is the better one.
4087
0
    const ObjCObjectPointerType* FromObjCPtr1
4088
0
      = FromType1->getAs<ObjCObjectPointerType>();
4089
0
    const ObjCObjectPointerType* FromObjCPtr2
4090
0
      = FromType2->getAs<ObjCObjectPointerType>();
4091
0
    if (FromObjCPtr1 && FromObjCPtr2) {
4092
0
      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4093
0
                                                          FromObjCPtr2);
4094
0
      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4095
0
                                                           FromObjCPtr1);
4096
0
      if (AssignLeft != AssignRight) {
4097
0
        return AssignLeft? ImplicitConversionSequence::Better
4098
0
                         : ImplicitConversionSequence::Worse;
4099
0
      }
4100
0
    }
4101
0
  }
4102
4103
1.75M
  if (SCS1.ReferenceBinding && 
SCS2.ReferenceBinding478k
) {
4104
    // Check for a better reference binding based on the kind of bindings.
4105
475k
    if (isBetterReferenceBindingKind(SCS1, SCS2))
4106
246k
      return ImplicitConversionSequence::Better;
4107
229k
    else if (isBetterReferenceBindingKind(SCS2, SCS1))
4108
6.38k
      return ImplicitConversionSequence::Worse;
4109
475k
  }
4110
4111
  // Compare based on qualification conversions (C++ 13.3.3.2p3,
4112
  // bullet 3).
4113
1.50M
  if (ImplicitConversionSequence::CompareKind QualCK
4114
1.50M
        = CompareQualificationConversions(S, SCS1, SCS2))
4115
203
    return QualCK;
4116
4117
1.50M
  if (SCS1.ReferenceBinding && 
SCS2.ReferenceBinding225k
) {
4118
    // C++ [over.ics.rank]p3b4:
4119
    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4120
    //      which the references refer are the same type except for
4121
    //      top-level cv-qualifiers, and the type to which the reference
4122
    //      initialized by S2 refers is more cv-qualified than the type
4123
    //      to which the reference initialized by S1 refers.
4124
222k
    QualType T1 = SCS1.getToType(2);
4125
222k
    QualType T2 = SCS2.getToType(2);
4126
222k
    T1 = S.Context.getCanonicalType(T1);
4127
222k
    T2 = S.Context.getCanonicalType(T2);
4128
222k
    Qualifiers T1Quals, T2Quals;
4129
222k
    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4130
222k
    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4131
222k
    if (UnqualT1 == UnqualT2) {
4132
      // Objective-C++ ARC: If the references refer to objects with different
4133
      // lifetimes, prefer bindings that don't change lifetime.
4134
222k
      if (SCS1.ObjCLifetimeConversionBinding !=
4135
222k
                                          SCS2.ObjCLifetimeConversionBinding) {
4136
2
        return SCS1.ObjCLifetimeConversionBinding
4137
2
                                           ? 
ImplicitConversionSequence::Worse0
4138
2
                                           : ImplicitConversionSequence::Better;
4139
2
      }
4140
4141
      // If the type is an array type, promote the element qualifiers to the
4142
      // type for comparison.
4143
222k
      if (isa<ArrayType>(T1) && 
T1Quals69
)
4144
63
        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4145
222k
      if (isa<ArrayType>(T2) && 
T2Quals69
)
4146
63
        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4147
222k
      if (T2.isMoreQualifiedThan(T1))
4148
57.2k
        return ImplicitConversionSequence::Better;
4149
165k
      if (T1.isMoreQualifiedThan(T2))
4150
36.7k
        return ImplicitConversionSequence::Worse;
4151
165k
    }
4152
222k
  }
4153
4154
  // In Microsoft mode (below 19.28), prefer an integral conversion to a
4155
  // floating-to-integral conversion if the integral conversion
4156
  // is between types of the same size.
4157
  // For example:
4158
  // void f(float);
4159
  // void f(int);
4160
  // int main {
4161
  //    long a;
4162
  //    f(a);
4163
  // }
4164
  // Here, MSVC will call f(int) instead of generating a compile error
4165
  // as clang will do in standard mode.
4166
1.41M
  if (S.getLangOpts().MSVCCompat &&
4167
1.41M
      
!S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8)16.1k
&&
4168
1.41M
      
SCS1.Second == ICK_Integral_Conversion16.1k
&&
4169
1.41M
      
SCS2.Second == ICK_Floating_Integral7.10k
&&
4170
1.41M
      S.Context.getTypeSize(SCS1.getFromType()) ==
4171
2.50k
          S.Context.getTypeSize(SCS1.getToType(2)))
4172
544
    return ImplicitConversionSequence::Better;
4173
4174
  // Prefer a compatible vector conversion over a lax vector conversion
4175
  // For example:
4176
  //
4177
  // typedef float __v4sf __attribute__((__vector_size__(16)));
4178
  // void f(vector float);
4179
  // void f(vector signed int);
4180
  // int main() {
4181
  //   __v4sf a;
4182
  //   f(a);
4183
  // }
4184
  // Here, we'd like to choose f(vector float) and not
4185
  // report an ambiguous call error
4186
1.41M
  if (SCS1.Second == ICK_Vector_Conversion &&
4187
1.41M
      
SCS2.Second == ICK_Vector_Conversion45.2k
) {
4188
45.2k
    bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4189
45.2k
        SCS1.getFromType(), SCS1.getToType(2));
4190
45.2k
    bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4191
45.2k
        SCS2.getFromType(), SCS2.getToType(2));
4192
4193
45.2k
    if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4194
743
      return SCS1IsCompatibleVectorConversion
4195
743
                 ? 
ImplicitConversionSequence::Better520
4196
743
                 : 
ImplicitConversionSequence::Worse223
;
4197
45.2k
  }
4198
4199
1.40M
  if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4200
1.40M
      
SCS2.Second == ICK_SVE_Vector_Conversion132
) {
4201
132
    bool SCS1IsCompatibleSVEVectorConversion =
4202
132
        S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4203
132
    bool SCS2IsCompatibleSVEVectorConversion =
4204
132
        S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4205
4206
132
    if (SCS1IsCompatibleSVEVectorConversion !=
4207
132
        SCS2IsCompatibleSVEVectorConversion)
4208
112
      return SCS1IsCompatibleSVEVectorConversion
4209
112
                 ? 
ImplicitConversionSequence::Better94
4210
112
                 : 
ImplicitConversionSequence::Worse18
;
4211
132
  }
4212
4213
1.40M
  return ImplicitConversionSequence::Indistinguishable;
4214
1.40M
}
4215
4216
/// CompareQualificationConversions - Compares two standard conversion
4217
/// sequences to determine whether they can be ranked based on their
4218
/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4219
static ImplicitConversionSequence::CompareKind
4220
CompareQualificationConversions(Sema &S,
4221
                                const StandardConversionSequence& SCS1,
4222
1.50M
                                const StandardConversionSequence& SCS2) {
4223
  // C++ [over.ics.rank]p3:
4224
  //  -- S1 and S2 differ only in their qualification conversion and
4225
  //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4226
  // [C++98]
4227
  //     [...] and the cv-qualification signature of type T1 is a proper subset
4228
  //     of the cv-qualification signature of type T2, and S1 is not the
4229
  //     deprecated string literal array-to-pointer conversion (4.2).
4230
  // [C++2a]
4231
  //     [...] where T1 can be converted to T2 by a qualification conversion.
4232
1.50M
  if (SCS1.First != SCS2.First || 
SCS1.Second != SCS2.Second1.50M
||
4233
1.50M
      
SCS1.Third != SCS2.Third1.37M
||
SCS1.Third != ICK_Qualification1.37M
)
4234
1.50M
    return ImplicitConversionSequence::Indistinguishable;
4235
4236
  // FIXME: the example in the standard doesn't use a qualification
4237
  // conversion (!)
4238
239
  QualType T1 = SCS1.getToType(2);
4239
239
  QualType T2 = SCS2.getToType(2);
4240
239
  T1 = S.Context.getCanonicalType(T1);
4241
239
  T2 = S.Context.getCanonicalType(T2);
4242
239
  assert(!T1->isReferenceType() && !T2->isReferenceType());
4243
0
  Qualifiers T1Quals, T2Quals;
4244
239
  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4245
239
  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4246
4247
  // If the types are the same, we won't learn anything by unwrapping
4248
  // them.
4249
239
  if (UnqualT1 == UnqualT2)
4250
8
    return ImplicitConversionSequence::Indistinguishable;
4251
4252
  // Don't ever prefer a standard conversion sequence that uses the deprecated
4253
  // string literal array to pointer conversion.
4254
231
  bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4255
231
  bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4256
4257
  // Objective-C++ ARC:
4258
  //   Prefer qualification conversions not involving a change in lifetime
4259
  //   to qualification conversions that do change lifetime.
4260
231
  if (SCS1.QualificationIncludesObjCLifetime &&
4261
231
      
!SCS2.QualificationIncludesObjCLifetime13
)
4262
1
    CanPick1 = false;
4263
231
  if (SCS2.QualificationIncludesObjCLifetime &&
4264
231
      
!SCS1.QualificationIncludesObjCLifetime15
)
4265
3
    CanPick2 = false;
4266
4267
231
  bool ObjCLifetimeConversion;
4268
231
  if (CanPick1 &&
4269
231
      
!S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)230
)
4270
120
    CanPick1 = false;
4271
  // FIXME: In Objective-C ARC, we can have qualification conversions in both
4272
  // directions, so we can't short-cut this second check in general.
4273
231
  if (CanPick2 &&
4274
231
      
!S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)228
)
4275
127
    CanPick2 = false;
4276
4277
231
  if (CanPick1 != CanPick2)
4278
203
    return CanPick1 ? 
ImplicitConversionSequence::Better106
4279
203
                    : 
ImplicitConversionSequence::Worse97
;
4280
28
  return ImplicitConversionSequence::Indistinguishable;
4281
231
}
4282
4283
/// CompareDerivedToBaseConversions - Compares two standard conversion
4284
/// sequences to determine whether they can be ranked based on their
4285
/// various kinds of derived-to-base conversions (C++
4286
/// [over.ics.rank]p4b3).  As part of these checks, we also look at
4287
/// conversions between Objective-C interface types.
4288
static ImplicitConversionSequence::CompareKind
4289
CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4290
                                const StandardConversionSequence& SCS1,
4291
1.75M
                                const StandardConversionSequence& SCS2) {
4292
1.75M
  QualType FromType1 = SCS1.getFromType();
4293
1.75M
  QualType ToType1 = SCS1.getToType(1);
4294
1.75M
  QualType FromType2 = SCS2.getFromType();
4295
1.75M
  QualType ToType2 = SCS2.getToType(1);
4296
4297
  // Adjust the types we're converting from via the array-to-pointer
4298
  // conversion, if we need to.
4299
1.75M
  if (SCS1.First == ICK_Array_To_Pointer)
4300
664
    FromType1 = S.Context.getArrayDecayedType(FromType1);
4301
1.75M
  if (SCS2.First == ICK_Array_To_Pointer)
4302
677
    FromType2 = S.Context.getArrayDecayedType(FromType2);
4303
4304
  // Canonicalize all of the types.
4305
1.75M
  FromType1 = S.Context.getCanonicalType(FromType1);
4306
1.75M
  ToType1 = S.Context.getCanonicalType(ToType1);
4307
1.75M
  FromType2 = S.Context.getCanonicalType(FromType2);
4308
1.75M
  ToType2 = S.Context.getCanonicalType(ToType2);
4309
4310
  // C++ [over.ics.rank]p4b3:
4311
  //
4312
  //   If class B is derived directly or indirectly from class A and
4313
  //   class C is derived directly or indirectly from B,
4314
  //
4315
  // Compare based on pointer conversions.
4316
1.75M
  if (SCS1.Second == ICK_Pointer_Conversion &&
4317
1.75M
      
SCS2.Second == ICK_Pointer_Conversion1.13k
&&
4318
      /*FIXME: Remove if Objective-C id conversions get their own rank*/
4319
1.75M
      
FromType1->isPointerType()1.13k
&&
FromType2->isPointerType()218
&&
4320
1.75M
      
ToType1->isPointerType()218
&&
ToType2->isPointerType()218
) {
4321
218
    QualType FromPointee1 =
4322
218
        FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4323
218
    QualType ToPointee1 =
4324
218
        ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4325
218
    QualType FromPointee2 =
4326
218
        FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4327
218
    QualType ToPointee2 =
4328
218
        ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4329
4330
    //   -- conversion of C* to B* is better than conversion of C* to A*,
4331
218
    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4332
44
      if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4333
10
        return ImplicitConversionSequence::Better;
4334
34
      else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4335
10
        return ImplicitConversionSequence::Worse;
4336
44
    }
4337
4338
    //   -- conversion of B* to A* is better than conversion of C* to A*,
4339
198
    if (FromPointee1 != FromPointee2 && 
ToPointee1 == ToPointee20
) {
4340
0
      if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4341
0
        return ImplicitConversionSequence::Better;
4342
0
      else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4343
0
        return ImplicitConversionSequence::Worse;
4344
0
    }
4345
1.75M
  } else if (SCS1.Second == ICK_Pointer_Conversion &&
4346
1.75M
             
SCS2.Second == ICK_Pointer_Conversion921
) {
4347
915
    const ObjCObjectPointerType *FromPtr1
4348
915
      = FromType1->getAs<ObjCObjectPointerType>();
4349
915
    const ObjCObjectPointerType *FromPtr2
4350
915
      = FromType2->getAs<ObjCObjectPointerType>();
4351
915
    const ObjCObjectPointerType *ToPtr1
4352
915
      = ToType1->getAs<ObjCObjectPointerType>();
4353
915
    const ObjCObjectPointerType *ToPtr2
4354
915
      = ToType2->getAs<ObjCObjectPointerType>();
4355
4356
915
    if (FromPtr1 && 
FromPtr234
&&
ToPtr134
&&
ToPtr234
) {
4357
      // Apply the same conversion ranking rules for Objective-C pointer types
4358
      // that we do for C++ pointers to class types. However, we employ the
4359
      // Objective-C pseudo-subtyping relationship used for assignment of
4360
      // Objective-C pointer types.
4361
34
      bool FromAssignLeft
4362
34
        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4363
34
      bool FromAssignRight
4364
34
        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4365
34
      bool ToAssignLeft
4366
34
        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4367
34
      bool ToAssignRight
4368
34
        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4369
4370
      // A conversion to an a non-id object pointer type or qualified 'id'
4371
      // type is better than a conversion to 'id'.
4372
34
      if (ToPtr1->isObjCIdType() &&
4373
34
          
(5
ToPtr2->isObjCQualifiedIdType()5
||
ToPtr2->getInterfaceDecl()5
))
4374
1
        return ImplicitConversionSequence::Worse;
4375
33
      if (ToPtr2->isObjCIdType() &&
4376
33
          
(9
ToPtr1->isObjCQualifiedIdType()9
||
ToPtr1->getInterfaceDecl()9
))
4377
5
        return ImplicitConversionSequence::Better;
4378
4379
      // A conversion to a non-id object pointer type is better than a
4380
      // conversion to a qualified 'id' type
4381
28
      if (ToPtr1->isObjCQualifiedIdType() && 
ToPtr2->getInterfaceDecl()4
)
4382
0
        return ImplicitConversionSequence::Worse;
4383
28
      if (ToPtr2->isObjCQualifiedIdType() && 
ToPtr1->getInterfaceDecl()6
)
4384
2
        return ImplicitConversionSequence::Better;
4385
4386
      // A conversion to an a non-Class object pointer type or qualified 'Class'
4387
      // type is better than a conversion to 'Class'.
4388
26
      if (ToPtr1->isObjCClassType() &&
4389
26
          
(0
ToPtr2->isObjCQualifiedClassType()0
||
ToPtr2->getInterfaceDecl()0
))
4390
0
        return ImplicitConversionSequence::Worse;
4391
26
      if (ToPtr2->isObjCClassType() &&
4392
26
          
(0
ToPtr1->isObjCQualifiedClassType()0
||
ToPtr1->getInterfaceDecl()0
))
4393
0
        return ImplicitConversionSequence::Better;
4394
4395
      // A conversion to a non-Class object pointer type is better than a
4396
      // conversion to a qualified 'Class' type.
4397
26
      if (ToPtr1->isObjCQualifiedClassType() && 
ToPtr2->getInterfaceDecl()0
)
4398
0
        return ImplicitConversionSequence::Worse;
4399
26
      if (ToPtr2->isObjCQualifiedClassType() && 
ToPtr1->getInterfaceDecl()0
)
4400
0
        return ImplicitConversionSequence::Better;
4401
4402
      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4403
26
      if (S.Context.hasSameType(FromType1, FromType2) &&
4404
26
          
!FromPtr1->isObjCIdType()14
&&
!FromPtr1->isObjCClassType()10
&&
4405
26
          
(ToAssignLeft != ToAssignRight)10
) {
4406
6
        if (FromPtr1->isSpecialized()) {
4407
          // "conversion of B<A> * to B * is better than conversion of B * to
4408
          // C *.
4409
4
          bool IsFirstSame =
4410
4
              FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4411
4
          bool IsSecondSame =
4412
4
              FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4413
4
          if (IsFirstSame) {
4414
3
            if (!IsSecondSame)
4415
3
              return ImplicitConversionSequence::Better;
4416
3
          } else 
if (1
IsSecondSame1
)
4417
1
            return ImplicitConversionSequence::Worse;
4418
4
        }
4419
2
        return ToAssignLeft? 
ImplicitConversionSequence::Worse1
4420
2
                           : 
ImplicitConversionSequence::Better1
;
4421
6
      }
4422
4423
      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4424
20
      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4425
20
          
(FromAssignLeft != FromAssignRight)12
)
4426
12
        return FromAssignLeft? ImplicitConversionSequence::Better
4427
12
        : 
ImplicitConversionSequence::Worse0
;
4428
20
    }
4429
915
  }
4430
4431
  // Ranking of member-pointer types.
4432
1.75M
  if (SCS1.Second == ICK_Pointer_Member && 
SCS2.Second == ICK_Pointer_Member557
&&
4433
1.75M
      
FromType1->isMemberPointerType()555
&&
FromType2->isMemberPointerType()24
&&
4434
1.75M
      
ToType1->isMemberPointerType()24
&&
ToType2->isMemberPointerType()24
) {
4435
24
    const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4436
24
    const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4437
24
    const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4438
24
    const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4439
24
    const Type *FromPointeeType1 = FromMemPointer1->getClass();
4440
24
    const Type *ToPointeeType1 = ToMemPointer1->getClass();
4441
24
    const Type *FromPointeeType2 = FromMemPointer2->getClass();
4442
24
    const Type *ToPointeeType2 = ToMemPointer2->getClass();
4443
24
    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4444
24
    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4445
24
    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4446
24
    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4447
    // conversion of A::* to B::* is better than conversion of A::* to C::*,
4448
24
    if (FromPointee1 == FromPointee2 && 
ToPointee1 != ToPointee28
) {
4449
8
      if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4450
2
        return ImplicitConversionSequence::Worse;
4451
6
      else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4452
6
        return ImplicitConversionSequence::Better;
4453
8
    }
4454
    // conversion of B::* to C::* is better than conversion of A::* to C::*
4455
16
    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4456
16
      if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4457
16
        return ImplicitConversionSequence::Better;
4458
0
      else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4459
0
        return ImplicitConversionSequence::Worse;
4460
16
    }
4461
16
  }
4462
4463
1.75M
  if (SCS1.Second == ICK_Derived_To_Base) {
4464
    //   -- conversion of C to B is better than conversion of C to A,
4465
    //   -- binding of an expression of type C to a reference of type
4466
    //      B& is better than binding an expression of type C to a
4467
    //      reference of type A&,
4468
5.97k
    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4469
5.97k
        
!S.Context.hasSameUnqualifiedType(ToType1, ToType2)5.94k
) {
4470
540
      if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4471
432
        return ImplicitConversionSequence::Better;
4472
108
      else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4473
12
        return ImplicitConversionSequence::Worse;
4474
540
    }
4475
4476
    //   -- conversion of B to A is better than conversion of C to A.
4477
    //   -- binding of an expression of type B to a reference of type
4478
    //      A& is better than binding an expression of type C to a
4479
    //      reference of type A&,
4480
5.53k
    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4481
5.53k
        
S.Context.hasSameUnqualifiedType(ToType1, ToType2)28
) {
4482
28
      if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4483
2
        return ImplicitConversionSequence::Better;
4484
26
      else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4485
2
        return ImplicitConversionSequence::Worse;
4486
28
    }
4487
5.53k
  }
4488
4489
1.75M
  return ImplicitConversionSequence::Indistinguishable;
4490
1.75M
}
4491
4492
/// Determine whether the given type is valid, e.g., it is not an invalid
4493
/// C++ class.
4494
9.34M
static bool isTypeValid(QualType T) {
4495
9.34M
  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4496
3.99M
    return !Record->isInvalidDecl();
4497
4498
5.35M
  return true;
4499
9.34M
}
4500
4501
10.2M
static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4502
10.2M
  if (!T.getQualifiers().hasUnaligned())
4503
10.2M
    return T;
4504
4505
15
  Qualifiers Q;
4506
15
  T = Ctx.getUnqualifiedArrayType(T, Q);
4507
15
  Q.removeUnaligned();
4508
15
  return Ctx.getQualifiedType(T, Q);
4509
10.2M
}
4510
4511
/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4512
/// determine whether they are reference-compatible,
4513
/// reference-related, or incompatible, for use in C++ initialization by
4514
/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4515
/// type, and the first type (T1) is the pointee type of the reference
4516
/// type being initialized.
4517
Sema::ReferenceCompareResult
4518
Sema::CompareReferenceRelationship(SourceLocation Loc,
4519
                                   QualType OrigT1, QualType OrigT2,
4520
5.86M
                                   ReferenceConversions *ConvOut) {
4521
5.86M
  assert(!OrigT1->isReferenceType() &&
4522
5.86M
    "T1 must be the pointee type of the reference type");
4523
0
  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4524
4525
0
  QualType T1 = Context.getCanonicalType(OrigT1);
4526
5.86M
  QualType T2 = Context.getCanonicalType(OrigT2);
4527
5.86M
  Qualifiers T1Quals, T2Quals;
4528
5.86M
  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4529
5.86M
  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4530
4531
5.86M
  ReferenceConversions ConvTmp;
4532
5.86M
  ReferenceConversions &Conv = ConvOut ? 
*ConvOut5.84M
:
ConvTmp13.6k
;
4533
5.86M
  Conv = ReferenceConversions();
4534
4535
  // C++2a [dcl.init.ref]p4:
4536
  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4537
  //   reference-related to "cv2 T2" if T1 is similar to T2, or
4538
  //   T1 is a base class of T2.
4539
  //   "cv1 T1" is reference-compatible with "cv2 T2" if
4540
  //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4541
  //   "pointer to cv1 T1" via a standard conversion sequence.
4542
4543
  // Check for standard conversions we can apply to pointers: derived-to-base
4544
  // conversions, ObjC pointer conversions, and function pointer conversions.
4545
  // (Qualification conversions are checked last.)
4546
5.86M
  QualType ConvertedT2;
4547
5.86M
  if (UnqualT1 == UnqualT2) {
4548
    // Nothing to do.
4549
4.67M
  } else if (isCompleteType(Loc, OrigT2) &&
4550
4.67M
             
isTypeValid(UnqualT1)4.67M
&&
isTypeValid(UnqualT2)4.67M
&&
4551
4.67M
             
IsDerivedFrom(Loc, UnqualT2, UnqualT1)4.67M
)
4552
15.8k
    Conv |= ReferenceConversions::DerivedToBase;
4553
4.66M
  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4554
4.66M
           
UnqualT2->isObjCObjectOrInterfaceType()47
&&
4555
4.66M
           
Context.canBindObjCObjectType(UnqualT1, UnqualT2)32
)
4556
32
    Conv |= ReferenceConversions::ObjC;
4557
4.66M
  else if (UnqualT2->isFunctionType() &&
4558
4.66M
           
IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)3.29k
) {
4559
36
    Conv |= ReferenceConversions::Function;
4560
    // No need to check qualifiers; function types don't have them.
4561
36
    return Ref_Compatible;
4562
36
  }
4563
5.86M
  bool ConvertedReferent = Conv != 0;
4564
4565
  // We can have a qualification conversion. Compute whether the types are
4566
  // similar at the same time.
4567
5.86M
  bool PreviousToQualsIncludeConst = true;
4568
5.86M
  bool TopLevel = true;
4569
5.86M
  do {
4570
5.86M
    if (T1 == T2)
4571
724k
      break;
4572
4573
    // We will need a qualification conversion.
4574
5.13M
    Conv |= ReferenceConversions::Qualification;
4575
4576
    // Track whether we performed a qualification conversion anywhere other
4577
    // than the top level. This matters for ranking reference bindings in
4578
    // overload resolution.
4579
5.13M
    if (!TopLevel)
4580
1.01k
      Conv |= ReferenceConversions::NestedQualification;
4581
4582
    // MS compiler ignores __unaligned qualifier for references; do the same.
4583
5.13M
    T1 = withoutUnaligned(Context, T1);
4584
5.13M
    T2 = withoutUnaligned(Context, T2);
4585
4586
    // If we find a qualifier mismatch, the types are not reference-compatible,
4587
    // but are still be reference-related if they're similar.
4588
5.13M
    bool ObjCLifetimeConversion = false;
4589
5.13M
    if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4590
5.13M
                                       PreviousToQualsIncludeConst,
4591
5.13M
                                       ObjCLifetimeConversion))
4592
91.8k
      return (ConvertedReferent || 
Context.hasSimilarType(T1, T2)91.4k
)
4593
91.8k
                 ? 
Ref_Related60.8k
4594
91.8k
                 : 
Ref_Incompatible30.9k
;
4595
4596
    // FIXME: Should we track this for any level other than the first?
4597
5.04M
    if (ObjCLifetimeConversion)
4598
38
      Conv |= ReferenceConversions::ObjCLifetime;
4599
4600
5.04M
    TopLevel = false;
4601
5.04M
  } while (Context.UnwrapSimilarTypes(T1, T2));
4602
4603
  // At this point, if the types are reference-related, we must either have the
4604
  // same inner type (ignoring qualifiers), or must have already worked out how
4605
  // to convert the referent.
4606
5.76M
  return (ConvertedReferent || 
Context.hasSameUnqualifiedType(T1, T2)5.75M
)
4607
5.76M
             ? 
Ref_Compatible1.13M
4608
5.76M
             : 
Ref_Incompatible4.63M
;
4609
5.86M
}
4610
4611
/// Look for a user-defined conversion to a value reference-compatible
4612
///        with DeclType. Return true if something definite is found.
4613
static bool
4614
FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4615
                         QualType DeclType, SourceLocation DeclLoc,
4616
                         Expr *Init, QualType T2, bool AllowRvalues,
4617
2.13M
                         bool AllowExplicit) {
4618
2.13M
  assert(T2->isRecordType() && "Can only find conversions of record types.");
4619
0
  auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4620
4621
2.13M
  OverloadCandidateSet CandidateSet(
4622
2.13M
      DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4623
2.13M
  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4624
2.63M
  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; 
++I498k
) {
4625
498k
    NamedDecl *D = *I;
4626
498k
    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4627
498k
    if (isa<UsingShadowDecl>(D))
4628
0
      D = cast<UsingShadowDecl>(D)->getTargetDecl();
4629
4630
498k
    FunctionTemplateDecl *ConvTemplate
4631
498k
      = dyn_cast<FunctionTemplateDecl>(D);
4632
498k
    CXXConversionDecl *Conv;
4633
498k
    if (ConvTemplate)
4634
56
      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4635
498k
    else
4636
498k
      Conv = cast<CXXConversionDecl>(D);
4637
4638
498k
    if (AllowRvalues) {
4639
      // If we are initializing an rvalue reference, don't permit conversion
4640
      // functions that return lvalues.
4641
10.6k
      if (!ConvTemplate && 
DeclType->isRValueReferenceType()10.5k
) {
4642
1.73k
        const ReferenceType *RefType
4643
1.73k
          = Conv->getConversionType()->getAs<LValueReferenceType>();
4644
1.73k
        if (RefType && 
!RefType->getPointeeType()->isFunctionType()94
)
4645
87
          continue;
4646
1.73k
      }
4647
4648
10.5k
      if (!ConvTemplate &&
4649
10.5k
          S.CompareReferenceRelationship(
4650
10.5k
              DeclLoc,
4651
10.5k
              Conv->getConversionType()
4652
10.5k
                  .getNonReferenceType()
4653
10.5k
                  .getUnqualifiedType(),
4654
10.5k
              DeclType.getNonReferenceType().getUnqualifiedType()) ==
4655
10.5k
              Sema::Ref_Incompatible)
4656
9.19k
        continue;
4657
487k
    } else {
4658
      // If the conversion function doesn't return a reference type,
4659
      // it can't be considered for this conversion. An rvalue reference
4660
      // is only acceptable if its referencee is a function type.
4661
4662
487k
      const ReferenceType *RefType =
4663
487k
        Conv->getConversionType()->getAs<ReferenceType>();
4664
487k
      if (!RefType ||
4665
487k
          
(42.7k
!RefType->isLValueReferenceType()42.7k
&&
4666
42.7k
           
!RefType->getPointeeType()->isFunctionType()2
))
4667
444k
        continue;
4668
487k
    }
4669
4670
44.1k
    if (ConvTemplate)
4671
41
      S.AddTemplateConversionCandidate(
4672
41
          ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4673
41
          /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4674
44.0k
    else
4675
44.0k
      S.AddConversionCandidate(
4676
44.0k
          Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4677
44.0k
          /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4678
44.1k
  }
4679
4680
2.13M
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4681
4682
2.13M
  OverloadCandidateSet::iterator Best;
4683
2.13M
  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4684
2.01k
  case OR_Success:
4685
    // C++ [over.ics.ref]p1:
4686
    //
4687
    //   [...] If the parameter binds directly to the result of
4688
    //   applying a conversion function to the argument
4689
    //   expression, the implicit conversion sequence is a
4690
    //   user-defined conversion sequence (13.3.3.1.2), with the
4691
    //   second standard conversion sequence either an identity
4692
    //   conversion or, if the conversion function returns an
4693
    //   entity of a type that is a derived class of the parameter
4694
    //   type, a derived-to-base Conversion.
4695
2.01k
    if (!Best->FinalConversion.DirectBinding)
4696
44
      return false;
4697
4698
1.97k
    ICS.setUserDefined();
4699
1.97k
    ICS.UserDefined.Before = Best->Conversions[0].Standard;
4700
1.97k
    ICS.UserDefined.After = Best->FinalConversion;
4701
1.97k
    ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4702
1.97k
    ICS.UserDefined.ConversionFunction = Best->Function;
4703
1.97k
    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4704
1.97k
    ICS.UserDefined.EllipsisConversion = false;
4705
1.97k
    assert(ICS.UserDefined.After.ReferenceBinding &&
4706
1.97k
           ICS.UserDefined.After.DirectBinding &&
4707
1.97k
           "Expected a direct reference binding!");
4708
0
    return true;
4709
4710
1
  case OR_Ambiguous:
4711
1
    ICS.setAmbiguous();
4712
1
    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4713
3
         Cand != CandidateSet.end(); 
++Cand2
)
4714
2
      if (Cand->Best)
4715
2
        ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4716
1
    return true;
4717
4718
2.13M
  case OR_No_Viable_Function:
4719
2.13M
  case OR_Deleted:
4720
    // There was no suitable conversion, or we found a deleted
4721
    // conversion; continue with other checks.
4722
2.13M
    return false;
4723
2.13M
  }
4724
4725
0
  llvm_unreachable("Invalid OverloadResult!");
4726
0
}
4727
4728
/// Compute an implicit conversion sequence for reference
4729
/// initialization.
4730
static ImplicitConversionSequence
4731
TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4732
                 SourceLocation DeclLoc,
4733
                 bool SuppressUserConversions,
4734
5.36M
                 bool AllowExplicit) {
4735
5.36M
  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4736
4737
  // Most paths end in a failed conversion.
4738
0
  ImplicitConversionSequence ICS;
4739
5.36M
  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4740
4741
5.36M
  QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4742
5.36M
  QualType T2 = Init->getType();
4743
4744
  // If the initializer is the address of an overloaded function, try
4745
  // to resolve the overloaded function. If all goes well, T2 is the
4746
  // type of the resulting function.
4747
5.36M
  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4748
343
    DeclAccessPair Found;
4749
343
    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4750
343
                                                                false, Found))
4751
81
      T2 = Fn->getType();
4752
343
  }
4753
4754
  // Compute some basic properties of the types and the initializer.
4755
5.36M
  bool isRValRef = DeclType->isRValueReferenceType();
4756
5.36M
  Expr::Classification InitCategory = Init->Classify(S.Context);
4757
4758
5.36M
  Sema::ReferenceConversions RefConv;
4759
5.36M
  Sema::ReferenceCompareResult RefRelationship =
4760
5.36M
      S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4761
4762
5.36M
  auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4763
610k
    ICS.setStandard();
4764
610k
    ICS.Standard.First = ICK_Identity;
4765
    // FIXME: A reference binding can be a function conversion too. We should
4766
    // consider that when ordering reference-to-function bindings.
4767
610k
    ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4768
610k
                              ? 
ICK_Derived_To_Base3.54k
4769
610k
                              : 
(RefConv & Sema::ReferenceConversions::ObjC)607k
4770
607k
                                    ? 
ICK_Compatible_Conversion17
4771
607k
                                    : 
ICK_Identity607k
;
4772
    // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4773
    // a reference binding that performs a non-top-level qualification
4774
    // conversion as a qualification conversion, not as an identity conversion.
4775
610k
    ICS.Standard.Third = (RefConv &
4776
610k
                              Sema::ReferenceConversions::NestedQualification)
4777
610k
                             ? 
ICK_Qualification17
4778
610k
                             : 
ICK_Identity610k
;
4779
610k
    ICS.Standard.setFromType(T2);
4780
610k
    ICS.Standard.setToType(0, T2);
4781
610k
    ICS.Standard.setToType(1, T1);
4782
610k
    ICS.Standard.setToType(2, T1);
4783
610k
    ICS.Standard.ReferenceBinding = true;
4784
610k
    ICS.Standard.DirectBinding = BindsDirectly;
4785
610k
    ICS.Standard.IsLvalueReference = !isRValRef;
4786
610k
    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4787
610k
    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4788
610k
    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4789
610k
    ICS.Standard.ObjCLifetimeConversionBinding =
4790
610k
        (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4791
610k
    ICS.Standard.CopyConstructor = nullptr;
4792
610k
    ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4793
610k
  };
4794
4795
  // C++0x [dcl.init.ref]p5:
4796
  //   A reference to type "cv1 T1" is initialized by an expression
4797
  //   of type "cv2 T2" as follows:
4798
4799
  //     -- If reference is an lvalue reference and the initializer expression
4800
5.36M
  if (!isRValRef) {
4801
    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4802
    //        reference-compatible with "cv2 T2," or
4803
    //
4804
    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4805
4.97M
    if (InitCategory.isLValue() && 
RefRelationship == Sema::Ref_Compatible4.60M
) {
4806
      // C++ [over.ics.ref]p1:
4807
      //   When a parameter of reference type binds directly (8.5.3)
4808
      //   to an argument expression, the implicit conversion sequence
4809
      //   is the identity conversion, unless the argument expression
4810
      //   has a type that is a derived class of the parameter type,
4811
      //   in which case the implicit conversion sequence is a
4812
      //   derived-to-base Conversion (13.3.3.1).
4813
298k
      SetAsReferenceBinding(/*BindsDirectly=*/true);
4814
4815
      // Nothing more to do: the inaccessibility/ambiguity check for
4816
      // derived-to-base conversions is suppressed when we're
4817
      // computing the implicit conversion sequence (C++
4818
      // [over.best.ics]p2).
4819
298k
      return ICS;
4820
298k
    }
4821
4822
    //       -- has a class type (i.e., T2 is a class type), where T1 is
4823
    //          not reference-related to T2, and can be implicitly
4824
    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4825
    //          is reference-compatible with "cv3 T3" 92) (this
4826
    //          conversion is selected by enumerating the applicable
4827
    //          conversion functions (13.3.1.6) and choosing the best
4828
    //          one through overload resolution (13.3)),
4829
4.67M
    if (!SuppressUserConversions && 
T2->isRecordType()2.31M
&&
4830
4.67M
        
S.isCompleteType(DeclLoc, T2)2.20M
&&
4831
4.67M
        
RefRelationship == Sema::Ref_Incompatible2.20M
) {
4832
2.08M
      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4833
2.08M
                                   Init, T2, /*AllowRvalues=*/false,
4834
2.08M
                                   AllowExplicit))
4835
700
        return ICS;
4836
2.08M
    }
4837
4.67M
  }
4838
4839
  //     -- Otherwise, the reference shall be an lvalue reference to a
4840
  //        non-volatile const type (i.e., cv1 shall be const), or the reference
4841
  //        shall be an rvalue reference.
4842
5.06M
  if (!isRValRef && 
(4.67M
!T1.isConstQualified()4.67M
||
T1.isVolatileQualified()474k
)) {
4843
4.19M
    if (InitCategory.isRValue() && 
RefRelationship != Sema::Ref_Incompatible33.7k
)
4844
477
      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4845
4.19M
    return ICS;
4846
4.19M
  }
4847
4848
  //       -- If the initializer expression
4849
  //
4850
  //            -- is an xvalue, class prvalue, array prvalue or function
4851
  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4852
872k
  if (RefRelationship == Sema::Ref_Compatible &&
4853
872k
      
(370k
InitCategory.isXValue()370k
||
4854
370k
       
(308k
InitCategory.isPRValue()308k
&&
4855
308k
          
(268k
T2->isRecordType()268k
||
T2->isArrayType()19.3k
)) ||
4856
370k
       
(58.6k
InitCategory.isLValue()58.6k
&&
T2->isFunctionType()39.2k
))) {
4857
    // In C++11, this is always a direct binding. In C++98/03, it's a direct
4858
    // binding unless we're binding to a class prvalue.
4859
    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4860
    // allow the use of rvalue references in C++98/03 for the benefit of
4861
    // standard library implementors; therefore, we need the xvalue check here.
4862
312k
    SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4863
312k
                          
!(4.37k
InitCategory.isPRValue()4.37k
||
T2->isRecordType()232
));
4864
312k
    return ICS;
4865
312k
  }
4866
4867
  //            -- has a class type (i.e., T2 is a class type), where T1 is not
4868
  //               reference-related to T2, and can be implicitly converted to
4869
  //               an xvalue, class prvalue, or function lvalue of type
4870
  //               "cv3 T3", where "cv1 T1" is reference-compatible with
4871
  //               "cv3 T3",
4872
  //
4873
  //          then the reference is bound to the value of the initializer
4874
  //          expression in the first case and to the result of the conversion
4875
  //          in the second case (or, in either case, to an appropriate base
4876
  //          class subobject).
4877
560k
  if (!SuppressUserConversions && 
RefRelationship == Sema::Ref_Incompatible206k
&&
4878
560k
      
T2->isRecordType()136k
&&
S.isCompleteType(DeclLoc, T2)54.0k
&&
4879
560k
      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4880
50.9k
                               Init, T2, /*AllowRvalues=*/true,
4881
50.9k
                               AllowExplicit)) {
4882
    // In the second case, if the reference is an rvalue reference
4883
    // and the second standard conversion sequence of the
4884
    // user-defined conversion sequence includes an lvalue-to-rvalue
4885
    // conversion, the program is ill-formed.
4886
1.27k
    if (ICS.isUserDefined() && isRValRef &&
4887
1.27k
        
ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue1.11k
)
4888
0
      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4889
4890
1.27k
    return ICS;
4891
1.27k
  }
4892
4893
  // A temporary of function type cannot be created; don't even try.
4894
558k
  if (T1->isFunctionType())
4895
28
    return ICS;
4896
4897
  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4898
  //          initialized from the initializer expression using the
4899
  //          rules for a non-reference copy initialization (8.5). The
4900
  //          reference is then bound to the temporary. If T1 is
4901
  //          reference-related to T2, cv1 must be the same
4902
  //          cv-qualification as, or greater cv-qualification than,
4903
  //          cv2; otherwise, the program is ill-formed.
4904
558k
  if (RefRelationship == Sema::Ref_Related) {
4905
    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4906
    // we would be reference-compatible or reference-compatible with
4907
    // added qualification. But that wasn't the case, so the reference
4908
    // initialization fails.
4909
    //
4910
    // Note that we only want to check address spaces and cvr-qualifiers here.
4911
    // ObjC GC, lifetime and unaligned qualifiers aren't important.
4912
59.3k
    Qualifiers T1Quals = T1.getQualifiers();
4913
59.3k
    Qualifiers T2Quals = T2.getQualifiers();
4914
59.3k
    T1Quals.removeObjCGCAttr();
4915
59.3k
    T1Quals.removeObjCLifetime();
4916
59.3k
    T2Quals.removeObjCGCAttr();
4917
59.3k
    T2Quals.removeObjCLifetime();
4918
    // MS compiler ignores __unaligned qualifier for references; do the same.
4919
59.3k
    T1Quals.removeUnaligned();
4920
59.3k
    T2Quals.removeUnaligned();
4921
59.3k
    if (!T1Quals.compatiblyIncludes(T2Quals))
4922
59.3k
      return ICS;
4923
59.3k
  }
4924
4925
  // If at least one of the types is a class type, the types are not
4926
  // related, and we aren't allowed any user conversions, the
4927
  // reference binding fails. This case is important for breaking
4928
  // recursion, since TryImplicitConversion below will attempt to
4929
  // create a temporary through the use of a copy constructor.
4930
499k
  if (SuppressUserConversions && 
RefRelationship == Sema::Ref_Incompatible306k
&&
4931
499k
      
(306k
T1->isRecordType()306k
||
T2->isRecordType()185
))
4932
306k
    return ICS;
4933
4934
  // If T1 is reference-related to T2 and the reference is an rvalue
4935
  // reference, the initializer expression shall not be an lvalue.
4936
193k
  if (RefRelationship >= Sema::Ref_Related && 
isRValRef57.8k
&&
4937
193k
      
Init->Classify(S.Context).isLValue()42.1k
) {
4938
38.4k
    ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4939
38.4k
    return ICS;
4940
38.4k
  }
4941
4942
  // C++ [over.ics.ref]p2:
4943
  //   When a parameter of reference type is not bound directly to
4944
  //   an argument expression, the conversion sequence is the one
4945
  //   required to convert the argument expression to the
4946
  //   underlying type of the reference according to
4947
  //   13.3.3.1. Conceptually, this conversion sequence corresponds
4948
  //   to copy-initializing a temporary of the underlying type with
4949
  //   the argument expression. Any difference in top-level
4950
  //   cv-qualification is subsumed by the initialization itself
4951
  //   and does not constitute a conversion.
4952
154k
  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4953
154k
                              AllowedExplicit::None,
4954
154k
                              /*InOverloadResolution=*/false,
4955
154k
                              /*CStyle=*/false,
4956
154k
                              /*AllowObjCWritebackConversion=*/false,
4957
154k
                              /*AllowObjCConversionOnExplicit=*/false);
4958
4959
  // Of course, that's still a reference binding.
4960
154k
  if (ICS.isStandard()) {
4961
21.3k
    ICS.Standard.ReferenceBinding = true;
4962
21.3k
    ICS.Standard.IsLvalueReference = !isRValRef;
4963
21.3k
    ICS.Standard.BindsToFunctionLvalue = false;
4964
21.3k
    ICS.Standard.BindsToRvalue = true;
4965
21.3k
    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4966
21.3k
    ICS.Standard.ObjCLifetimeConversionBinding = false;
4967
133k
  } else if (ICS.isUserDefined()) {
4968
27.0k
    const ReferenceType *LValRefType =
4969
27.0k
        ICS.UserDefined.ConversionFunction->getReturnType()
4970
27.0k
            ->getAs<LValueReferenceType>();
4971
4972
    // C++ [over.ics.ref]p3:
4973
    //   Except for an implicit object parameter, for which see 13.3.1, a
4974
    //   standard conversion sequence cannot be formed if it requires [...]
4975
    //   binding an rvalue reference to an lvalue other than a function
4976
    //   lvalue.
4977
    // Note that the function case is not possible here.
4978
27.0k
    if (isRValRef && 
LValRefType9.29k
) {
4979
25
      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4980
25
      return ICS;
4981
25
    }
4982
4983
27.0k
    ICS.UserDefined.After.ReferenceBinding = true;
4984
27.0k
    ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4985
27.0k
    ICS.UserDefined.After.BindsToFunctionLvalue = false;
4986
27.0k
    ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4987
27.0k
    ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4988
27.0k
    ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4989
27.0k
  }
4990
4991
154k
  return ICS;
4992
154k
}
4993
4994
static ImplicitConversionSequence
4995
TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4996
                      bool SuppressUserConversions,
4997
                      bool InOverloadResolution,
4998
                      bool AllowObjCWritebackConversion,
4999
                      bool AllowExplicit = false);
5000
5001
/// TryListConversion - Try to copy-initialize a value of type ToType from the
5002
/// initializer list From.
5003
static ImplicitConversionSequence
5004
TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5005
                  bool SuppressUserConversions,
5006
                  bool InOverloadResolution,
5007
4.43k
                  bool AllowObjCWritebackConversi