Coverage Report

Created: 2020-02-25 14:32

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