Coverage Report

Created: 2022-05-21 09:15

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