xref: /llvm-project/clang/include/clang/Sema/Overload.h (revision 28ad8978ee2054298d4198bf10c8cb68730af037)
1 //===- Overload.h - C++ Overloading -----------------------------*- C++ -*-===//
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 defines the data structures and types used in C++
10 // overload resolution.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_SEMA_OVERLOAD_H
15 #define LLVM_CLANG_SEMA_OVERLOAD_H
16 
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclAccessPair.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/LLVM.h"
25 #include "clang/Basic/SourceLocation.h"
26 #include "clang/Sema/SemaFixItUtils.h"
27 #include "clang/Sema/TemplateDeduction.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Support/AlignOf.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include <cassert>
38 #include <cstddef>
39 #include <cstdint>
40 #include <utility>
41 
42 namespace clang {
43 
44 class APValue;
45 class ASTContext;
46 class Sema;
47 
48   /// OverloadingResult - Capture the result of performing overload
49   /// resolution.
50   enum OverloadingResult {
51     /// Overload resolution succeeded.
52     OR_Success,
53 
54     /// No viable function found.
55     OR_No_Viable_Function,
56 
57     /// Ambiguous candidates found.
58     OR_Ambiguous,
59 
60     /// Succeeded, but refers to a deleted function.
61     OR_Deleted
62   };
63 
64   enum OverloadCandidateDisplayKind {
65     /// Requests that all candidates be shown.  Viable candidates will
66     /// be printed first.
67     OCD_AllCandidates,
68 
69     /// Requests that only viable candidates be shown.
70     OCD_ViableCandidates,
71 
72     /// Requests that only tied-for-best candidates be shown.
73     OCD_AmbiguousCandidates
74   };
75 
76   /// The parameter ordering that will be used for the candidate. This is
77   /// used to represent C++20 binary operator rewrites that reverse the order
78   /// of the arguments. If the parameter ordering is Reversed, the Args list is
79   /// reversed (but obviously the ParamDecls for the function are not).
80   ///
81   /// After forming an OverloadCandidate with reversed parameters, the list
82   /// of conversions will (as always) be indexed by argument, so will be
83   /// in reverse parameter order.
84   enum class OverloadCandidateParamOrder : char { Normal, Reversed };
85 
86   /// The kinds of rewrite we perform on overload candidates. Note that the
87   /// values here are chosen to serve as both bitflags and as a rank (lower
88   /// values are preferred by overload resolution).
89   enum OverloadCandidateRewriteKind : unsigned {
90     /// Candidate is not a rewritten candidate.
91     CRK_None = 0x0,
92 
93     /// Candidate is a rewritten candidate with a different operator name.
94     CRK_DifferentOperator = 0x1,
95 
96     /// Candidate is a rewritten candidate with a reversed order of parameters.
97     CRK_Reversed = 0x2,
98   };
99 
100   /// ImplicitConversionKind - The kind of implicit conversion used to
101   /// convert an argument to a parameter's type. The enumerator values
102   /// match with the table titled 'Conversions' in [over.ics.scs] and are listed
103   /// such that better conversion kinds have smaller values.
104   enum ImplicitConversionKind {
105     /// Identity conversion (no conversion)
106     ICK_Identity = 0,
107 
108     /// Lvalue-to-rvalue conversion (C++ [conv.lval])
109     ICK_Lvalue_To_Rvalue,
110 
111     /// Array-to-pointer conversion (C++ [conv.array])
112     ICK_Array_To_Pointer,
113 
114     /// Function-to-pointer (C++ [conv.array])
115     ICK_Function_To_Pointer,
116 
117     /// Function pointer conversion (C++17 [conv.fctptr])
118     ICK_Function_Conversion,
119 
120     /// Qualification conversions (C++ [conv.qual])
121     ICK_Qualification,
122 
123     /// Integral promotions (C++ [conv.prom])
124     ICK_Integral_Promotion,
125 
126     /// Floating point promotions (C++ [conv.fpprom])
127     ICK_Floating_Promotion,
128 
129     /// Complex promotions (Clang extension)
130     ICK_Complex_Promotion,
131 
132     /// Integral conversions (C++ [conv.integral])
133     ICK_Integral_Conversion,
134 
135     /// Floating point conversions (C++ [conv.double]
136     ICK_Floating_Conversion,
137 
138     /// Complex conversions (C99 6.3.1.6)
139     ICK_Complex_Conversion,
140 
141     /// Floating-integral conversions (C++ [conv.fpint])
142     ICK_Floating_Integral,
143 
144     /// Pointer conversions (C++ [conv.ptr])
145     ICK_Pointer_Conversion,
146 
147     /// Pointer-to-member conversions (C++ [conv.mem])
148     ICK_Pointer_Member,
149 
150     /// Boolean conversions (C++ [conv.bool])
151     ICK_Boolean_Conversion,
152 
153     /// Conversions between compatible types in C99
154     ICK_Compatible_Conversion,
155 
156     /// Derived-to-base (C++ [over.best.ics])
157     ICK_Derived_To_Base,
158 
159     /// Vector conversions
160     ICK_Vector_Conversion,
161 
162     /// Arm SVE Vector conversions
163     ICK_SVE_Vector_Conversion,
164 
165     /// RISC-V RVV Vector conversions
166     ICK_RVV_Vector_Conversion,
167 
168     /// A vector splat from an arithmetic type
169     ICK_Vector_Splat,
170 
171     /// Complex-real conversions (C99 6.3.1.7)
172     ICK_Complex_Real,
173 
174     /// Block Pointer conversions
175     ICK_Block_Pointer_Conversion,
176 
177     /// Transparent Union Conversions
178     ICK_TransparentUnionConversion,
179 
180     /// Objective-C ARC writeback conversion
181     ICK_Writeback_Conversion,
182 
183     /// Zero constant to event (OpenCL1.2 6.12.10)
184     ICK_Zero_Event_Conversion,
185 
186     /// Zero constant to queue
187     ICK_Zero_Queue_Conversion,
188 
189     /// Conversions allowed in C, but not C++
190     ICK_C_Only_Conversion,
191 
192     /// C-only conversion between pointers with incompatible types
193     ICK_Incompatible_Pointer_Conversion,
194 
195     /// Fixed point type conversions according to N1169.
196     ICK_Fixed_Point_Conversion,
197 
198     /// HLSL vector truncation.
199     ICK_HLSL_Vector_Truncation,
200 
201     /// HLSL non-decaying array rvalue cast.
202     ICK_HLSL_Array_RValue,
203 
204     // HLSL vector splat from scalar or boolean type.
205     ICK_HLSL_Vector_Splat,
206 
207     /// The number of conversion kinds
208     ICK_Num_Conversion_Kinds,
209   };
210 
211   /// ImplicitConversionRank - The rank of an implicit conversion
212   /// kind. The enumerator values match with Table 9 of (C++
213   /// 13.3.3.1.1) and are listed such that better conversion ranks
214   /// have smaller values.
215   enum ImplicitConversionRank {
216     /// Exact Match
217     ICR_Exact_Match = 0,
218 
219     /// HLSL Scalar Widening
220     ICR_HLSL_Scalar_Widening,
221 
222     /// Promotion
223     ICR_Promotion,
224 
225     /// HLSL Scalar Widening with promotion
226     ICR_HLSL_Scalar_Widening_Promotion,
227 
228     /// Conversion
229     ICR_Conversion,
230 
231     /// OpenCL Scalar Widening
232     ICR_OCL_Scalar_Widening,
233 
234     /// HLSL Scalar Widening with conversion
235     ICR_HLSL_Scalar_Widening_Conversion,
236 
237     /// Complex <-> Real conversion
238     ICR_Complex_Real_Conversion,
239 
240     /// ObjC ARC writeback conversion
241     ICR_Writeback_Conversion,
242 
243     /// Conversion only allowed in the C standard (e.g. void* to char*).
244     ICR_C_Conversion,
245 
246     /// Conversion not allowed by the C standard, but that we accept as an
247     /// extension anyway.
248     ICR_C_Conversion_Extension,
249 
250     /// HLSL Matching Dimension Reduction
251     ICR_HLSL_Dimension_Reduction,
252 
253     /// HLSL Dimension reduction with promotion
254     ICR_HLSL_Dimension_Reduction_Promotion,
255 
256     /// HLSL Dimension reduction with conversion
257     ICR_HLSL_Dimension_Reduction_Conversion,
258   };
259 
260   ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
261 
262   ImplicitConversionRank
263   GetDimensionConversionRank(ImplicitConversionRank Base,
264                              ImplicitConversionKind Dimension);
265 
266   /// NarrowingKind - The kind of narrowing conversion being performed by a
267   /// standard conversion sequence according to C++11 [dcl.init.list]p7.
268   enum NarrowingKind {
269     /// Not a narrowing conversion.
270     NK_Not_Narrowing,
271 
272     /// A narrowing conversion by virtue of the source and destination types.
273     NK_Type_Narrowing,
274 
275     /// A narrowing conversion, because a constant expression got narrowed.
276     NK_Constant_Narrowing,
277 
278     /// A narrowing conversion, because a non-constant-expression variable might
279     /// have got narrowed.
280     NK_Variable_Narrowing,
281 
282     /// Cannot tell whether this is a narrowing conversion because the
283     /// expression is value-dependent.
284     NK_Dependent_Narrowing,
285   };
286 
287   /// StandardConversionSequence - represents a standard conversion
288   /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
289   /// contains between zero and three conversions. If a particular
290   /// conversion is not needed, it will be set to the identity conversion
291   /// (ICK_Identity).
292   class StandardConversionSequence {
293   public:
294     /// First -- The first conversion can be an lvalue-to-rvalue
295     /// conversion, array-to-pointer conversion, or
296     /// function-to-pointer conversion.
297     ImplicitConversionKind First : 8;
298 
299     /// Second - The second conversion can be an integral promotion,
300     /// floating point promotion, integral conversion, floating point
301     /// conversion, floating-integral conversion, pointer conversion,
302     /// pointer-to-member conversion, or boolean conversion.
303     ImplicitConversionKind Second : 8;
304 
305     /// Dimension - Between the second and third conversion a vector or matrix
306     /// dimension conversion may occur. If this is not ICK_Identity this
307     /// conversion truncates the vector or matrix, or extends a scalar.
308     ImplicitConversionKind Dimension : 8;
309 
310     /// Third - The third conversion can be a qualification conversion
311     /// or a function conversion.
312     ImplicitConversionKind Third : 8;
313 
314     /// Whether this is the deprecated conversion of a
315     /// string literal to a pointer to non-const character data
316     /// (C++ 4.2p2).
317     LLVM_PREFERRED_TYPE(bool)
318     unsigned DeprecatedStringLiteralToCharPtr : 1;
319 
320     /// Whether the qualification conversion involves a change in the
321     /// Objective-C lifetime (for automatic reference counting).
322     LLVM_PREFERRED_TYPE(bool)
323     unsigned QualificationIncludesObjCLifetime : 1;
324 
325     /// IncompatibleObjC - Whether this is an Objective-C conversion
326     /// that we should warn about (if we actually use it).
327     LLVM_PREFERRED_TYPE(bool)
328     unsigned IncompatibleObjC : 1;
329 
330     /// ReferenceBinding - True when this is a reference binding
331     /// (C++ [over.ics.ref]).
332     LLVM_PREFERRED_TYPE(bool)
333     unsigned ReferenceBinding : 1;
334 
335     /// DirectBinding - True when this is a reference binding that is a
336     /// direct binding (C++ [dcl.init.ref]).
337     LLVM_PREFERRED_TYPE(bool)
338     unsigned DirectBinding : 1;
339 
340     /// Whether this is an lvalue reference binding (otherwise, it's
341     /// an rvalue reference binding).
342     LLVM_PREFERRED_TYPE(bool)
343     unsigned IsLvalueReference : 1;
344 
345     /// Whether we're binding to a function lvalue.
346     LLVM_PREFERRED_TYPE(bool)
347     unsigned BindsToFunctionLvalue : 1;
348 
349     /// Whether we're binding to an rvalue.
350     LLVM_PREFERRED_TYPE(bool)
351     unsigned BindsToRvalue : 1;
352 
353     /// Whether this binds an implicit object argument to a
354     /// non-static member function without a ref-qualifier.
355     LLVM_PREFERRED_TYPE(bool)
356     unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
357 
358     /// Whether this binds a reference to an object with a different
359     /// Objective-C lifetime qualifier.
360     LLVM_PREFERRED_TYPE(bool)
361     unsigned ObjCLifetimeConversionBinding : 1;
362 
363     /// FromType - The type that this conversion is converting
364     /// from. This is an opaque pointer that can be translated into a
365     /// QualType.
366     void *FromTypePtr;
367 
368     /// ToType - The types that this conversion is converting to in
369     /// each step. This is an opaque pointer that can be translated
370     /// into a QualType.
371     void *ToTypePtrs[3];
372 
373     /// CopyConstructor - The copy constructor that is used to perform
374     /// this conversion, when the conversion is actually just the
375     /// initialization of an object via copy constructor. Such
376     /// conversions are either identity conversions or derived-to-base
377     /// conversions.
378     CXXConstructorDecl *CopyConstructor;
379     DeclAccessPair FoundCopyConstructor;
380 
381     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
382 
383     void setToType(unsigned Idx, QualType T) {
384       assert(Idx < 3 && "To type index is out of range");
385       ToTypePtrs[Idx] = T.getAsOpaquePtr();
386     }
387 
388     void setAllToTypes(QualType T) {
389       ToTypePtrs[0] = T.getAsOpaquePtr();
390       ToTypePtrs[1] = ToTypePtrs[0];
391       ToTypePtrs[2] = ToTypePtrs[0];
392     }
393 
394     QualType getFromType() const {
395       return QualType::getFromOpaquePtr(FromTypePtr);
396     }
397 
398     QualType getToType(unsigned Idx) const {
399       assert(Idx < 3 && "To type index is out of range");
400       return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
401     }
402 
403     void setAsIdentityConversion();
404 
405     bool isIdentityConversion() const {
406       return Second == ICK_Identity && Dimension == ICK_Identity &&
407              Third == ICK_Identity;
408     }
409 
410     ImplicitConversionRank getRank() const;
411     NarrowingKind
412     getNarrowingKind(ASTContext &Context, const Expr *Converted,
413                      APValue &ConstantValue, QualType &ConstantType,
414                      bool IgnoreFloatToIntegralConversion = false) const;
415     bool isPointerConversionToBool() const;
416     bool isPointerConversionToVoidPointer(ASTContext& Context) const;
417     void dump() const;
418   };
419 
420   /// UserDefinedConversionSequence - Represents a user-defined
421   /// conversion sequence (C++ 13.3.3.1.2).
422   struct UserDefinedConversionSequence {
423     /// Represents the standard conversion that occurs before
424     /// the actual user-defined conversion.
425     ///
426     /// C++11 13.3.3.1.2p1:
427     ///   If the user-defined conversion is specified by a constructor
428     ///   (12.3.1), the initial standard conversion sequence converts
429     ///   the source type to the type required by the argument of the
430     ///   constructor. If the user-defined conversion is specified by
431     ///   a conversion function (12.3.2), the initial standard
432     ///   conversion sequence converts the source type to the implicit
433     ///   object parameter of the conversion function.
434     StandardConversionSequence Before;
435 
436     /// EllipsisConversion - When this is true, it means user-defined
437     /// conversion sequence starts with a ... (ellipsis) conversion, instead of
438     /// a standard conversion. In this case, 'Before' field must be ignored.
439     // FIXME. I much rather put this as the first field. But there seems to be
440     // a gcc code gen. bug which causes a crash in a test. Putting it here seems
441     // to work around the crash.
442     bool EllipsisConversion : 1;
443 
444     /// HadMultipleCandidates - When this is true, it means that the
445     /// conversion function was resolved from an overloaded set having
446     /// size greater than 1.
447     bool HadMultipleCandidates : 1;
448 
449     /// After - Represents the standard conversion that occurs after
450     /// the actual user-defined conversion.
451     StandardConversionSequence After;
452 
453     /// ConversionFunction - The function that will perform the
454     /// user-defined conversion. Null if the conversion is an
455     /// aggregate initialization from an initializer list.
456     FunctionDecl* ConversionFunction;
457 
458     /// The declaration that we found via name lookup, which might be
459     /// the same as \c ConversionFunction or it might be a using declaration
460     /// that refers to \c ConversionFunction.
461     DeclAccessPair FoundConversionFunction;
462 
463     void dump() const;
464   };
465 
466   /// Represents an ambiguous user-defined conversion sequence.
467   struct AmbiguousConversionSequence {
468     using ConversionSet =
469         SmallVector<std::pair<NamedDecl *, FunctionDecl *>, 4>;
470 
471     void *FromTypePtr;
472     void *ToTypePtr;
473     char Buffer[sizeof(ConversionSet)];
474 
475     QualType getFromType() const {
476       return QualType::getFromOpaquePtr(FromTypePtr);
477     }
478 
479     QualType getToType() const {
480       return QualType::getFromOpaquePtr(ToTypePtr);
481     }
482 
483     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
484     void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
485 
486     ConversionSet &conversions() {
487       return *reinterpret_cast<ConversionSet*>(Buffer);
488     }
489 
490     const ConversionSet &conversions() const {
491       return *reinterpret_cast<const ConversionSet*>(Buffer);
492     }
493 
494     void addConversion(NamedDecl *Found, FunctionDecl *D) {
495       conversions().push_back(std::make_pair(Found, D));
496     }
497 
498     using iterator = ConversionSet::iterator;
499 
500     iterator begin() { return conversions().begin(); }
501     iterator end() { return conversions().end(); }
502 
503     using const_iterator = ConversionSet::const_iterator;
504 
505     const_iterator begin() const { return conversions().begin(); }
506     const_iterator end() const { return conversions().end(); }
507 
508     void construct();
509     void destruct();
510     void copyFrom(const AmbiguousConversionSequence &);
511   };
512 
513   /// BadConversionSequence - Records information about an invalid
514   /// conversion sequence.
515   struct BadConversionSequence {
516     enum FailureKind {
517       no_conversion,
518       unrelated_class,
519       bad_qualifiers,
520       lvalue_ref_to_rvalue,
521       rvalue_ref_to_lvalue,
522       too_few_initializers,
523       too_many_initializers,
524     };
525 
526     // This can be null, e.g. for implicit object arguments.
527     Expr *FromExpr;
528 
529     FailureKind Kind;
530 
531   private:
532     // The type we're converting from (an opaque QualType).
533     void *FromTy;
534 
535     // The type we're converting to (an opaque QualType).
536     void *ToTy;
537 
538   public:
539     void init(FailureKind K, Expr *From, QualType To) {
540       init(K, From->getType(), To);
541       FromExpr = From;
542     }
543 
544     void init(FailureKind K, QualType From, QualType To) {
545       Kind = K;
546       FromExpr = nullptr;
547       setFromType(From);
548       setToType(To);
549     }
550 
551     QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
552     QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
553 
554     void setFromExpr(Expr *E) {
555       FromExpr = E;
556       setFromType(E->getType());
557     }
558 
559     void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
560     void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
561   };
562 
563   /// ImplicitConversionSequence - Represents an implicit conversion
564   /// sequence, which may be a standard conversion sequence
565   /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
566   /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
567   class ImplicitConversionSequence {
568   public:
569     /// Kind - The kind of implicit conversion sequence. BadConversion
570     /// specifies that there is no conversion from the source type to
571     /// the target type.  AmbiguousConversion represents the unique
572     /// ambiguous conversion (C++0x [over.best.ics]p10).
573     /// StaticObjectArgumentConversion represents the conversion rules for
574     /// the synthesized first argument of calls to static member functions
575     /// ([over.best.ics.general]p8).
576     enum Kind {
577       StandardConversion = 0,
578       StaticObjectArgumentConversion,
579       UserDefinedConversion,
580       AmbiguousConversion,
581       EllipsisConversion,
582       BadConversion
583     };
584 
585   private:
586     enum {
587       Uninitialized = BadConversion + 1
588     };
589 
590     /// ConversionKind - The kind of implicit conversion sequence.
591     LLVM_PREFERRED_TYPE(Kind)
592     unsigned ConversionKind : 31;
593 
594     // Whether the initializer list was of an incomplete array.
595     LLVM_PREFERRED_TYPE(bool)
596     unsigned InitializerListOfIncompleteArray : 1;
597 
598     /// When initializing an array or std::initializer_list from an
599     /// initializer-list, this is the array or std::initializer_list type being
600     /// initialized. The remainder of the conversion sequence, including ToType,
601     /// describe the worst conversion of an initializer to an element of the
602     /// array or std::initializer_list. (Note, 'worst' is not well defined.)
603     QualType InitializerListContainerType;
604 
605     void setKind(Kind K) {
606       destruct();
607       ConversionKind = K;
608     }
609 
610     void destruct() {
611       if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
612     }
613 
614   public:
615     union {
616       /// When ConversionKind == StandardConversion, provides the
617       /// details of the standard conversion sequence.
618       StandardConversionSequence Standard;
619 
620       /// When ConversionKind == UserDefinedConversion, provides the
621       /// details of the user-defined conversion sequence.
622       UserDefinedConversionSequence UserDefined;
623 
624       /// When ConversionKind == AmbiguousConversion, provides the
625       /// details of the ambiguous conversion.
626       AmbiguousConversionSequence Ambiguous;
627 
628       /// When ConversionKind == BadConversion, provides the details
629       /// of the bad conversion.
630       BadConversionSequence Bad;
631     };
632 
633     ImplicitConversionSequence()
634         : ConversionKind(Uninitialized),
635           InitializerListOfIncompleteArray(false) {
636       Standard.setAsIdentityConversion();
637     }
638 
639     ImplicitConversionSequence(const ImplicitConversionSequence &Other)
640         : ConversionKind(Other.ConversionKind),
641           InitializerListOfIncompleteArray(
642               Other.InitializerListOfIncompleteArray),
643           InitializerListContainerType(Other.InitializerListContainerType) {
644       switch (ConversionKind) {
645       case Uninitialized: break;
646       case StandardConversion: Standard = Other.Standard; break;
647       case StaticObjectArgumentConversion:
648         break;
649       case UserDefinedConversion: UserDefined = Other.UserDefined; break;
650       case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
651       case EllipsisConversion: break;
652       case BadConversion: Bad = Other.Bad; break;
653       }
654     }
655 
656     ImplicitConversionSequence &
657     operator=(const ImplicitConversionSequence &Other) {
658       destruct();
659       new (this) ImplicitConversionSequence(Other);
660       return *this;
661     }
662 
663     ~ImplicitConversionSequence() {
664       destruct();
665     }
666 
667     Kind getKind() const {
668       assert(isInitialized() && "querying uninitialized conversion");
669       return Kind(ConversionKind);
670     }
671 
672     /// Return a ranking of the implicit conversion sequence
673     /// kind, where smaller ranks represent better conversion
674     /// sequences.
675     ///
676     /// In particular, this routine gives user-defined conversion
677     /// sequences and ambiguous conversion sequences the same rank,
678     /// per C++ [over.best.ics]p10.
679     unsigned getKindRank() const {
680       switch (getKind()) {
681       case StandardConversion:
682       case StaticObjectArgumentConversion:
683         return 0;
684 
685       case UserDefinedConversion:
686       case AmbiguousConversion:
687         return 1;
688 
689       case EllipsisConversion:
690         return 2;
691 
692       case BadConversion:
693         return 3;
694       }
695 
696       llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
697     }
698 
699     bool isBad() const { return getKind() == BadConversion; }
700     bool isStandard() const { return getKind() == StandardConversion; }
701     bool isStaticObjectArgument() const {
702       return getKind() == StaticObjectArgumentConversion;
703     }
704     bool isEllipsis() const { return getKind() == EllipsisConversion; }
705     bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
706     bool isUserDefined() const { return getKind() == UserDefinedConversion; }
707     bool isFailure() const { return isBad() || isAmbiguous(); }
708 
709     /// Determines whether this conversion sequence has been
710     /// initialized.  Most operations should never need to query
711     /// uninitialized conversions and should assert as above.
712     bool isInitialized() const { return ConversionKind != Uninitialized; }
713 
714     /// Sets this sequence as a bad conversion for an explicit argument.
715     void setBad(BadConversionSequence::FailureKind Failure,
716                 Expr *FromExpr, QualType ToType) {
717       setKind(BadConversion);
718       Bad.init(Failure, FromExpr, ToType);
719     }
720 
721     /// Sets this sequence as a bad conversion for an implicit argument.
722     void setBad(BadConversionSequence::FailureKind Failure,
723                 QualType FromType, QualType ToType) {
724       setKind(BadConversion);
725       Bad.init(Failure, FromType, ToType);
726     }
727 
728     void setStandard() { setKind(StandardConversion); }
729     void setStaticObjectArgument() { setKind(StaticObjectArgumentConversion); }
730     void setEllipsis() { setKind(EllipsisConversion); }
731     void setUserDefined() { setKind(UserDefinedConversion); }
732 
733     void setAmbiguous() {
734       if (ConversionKind == AmbiguousConversion) return;
735       ConversionKind = AmbiguousConversion;
736       Ambiguous.construct();
737     }
738 
739     void setAsIdentityConversion(QualType T) {
740       setStandard();
741       Standard.setAsIdentityConversion();
742       Standard.setFromType(T);
743       Standard.setAllToTypes(T);
744     }
745 
746     // True iff this is a conversion sequence from an initializer list to an
747     // array or std::initializer.
748     bool hasInitializerListContainerType() const {
749       return !InitializerListContainerType.isNull();
750     }
751     void setInitializerListContainerType(QualType T, bool IA) {
752       InitializerListContainerType = T;
753       InitializerListOfIncompleteArray = IA;
754     }
755     bool isInitializerListOfIncompleteArray() const {
756       return InitializerListOfIncompleteArray;
757     }
758     QualType getInitializerListContainerType() const {
759       assert(hasInitializerListContainerType() &&
760              "not initializer list container");
761       return InitializerListContainerType;
762     }
763 
764     /// Form an "implicit" conversion sequence from nullptr_t to bool, for a
765     /// direct-initialization of a bool object from nullptr_t.
766     static ImplicitConversionSequence getNullptrToBool(QualType SourceType,
767                                                        QualType DestType,
768                                                        bool NeedLValToRVal) {
769       ImplicitConversionSequence ICS;
770       ICS.setStandard();
771       ICS.Standard.setAsIdentityConversion();
772       ICS.Standard.setFromType(SourceType);
773       if (NeedLValToRVal)
774         ICS.Standard.First = ICK_Lvalue_To_Rvalue;
775       ICS.Standard.setToType(0, SourceType);
776       ICS.Standard.Second = ICK_Boolean_Conversion;
777       ICS.Standard.setToType(1, DestType);
778       ICS.Standard.setToType(2, DestType);
779       return ICS;
780     }
781 
782     // The result of a comparison between implicit conversion
783     // sequences. Use Sema::CompareImplicitConversionSequences to
784     // actually perform the comparison.
785     enum CompareKind {
786       Better = -1,
787       Indistinguishable = 0,
788       Worse = 1
789     };
790 
791     void DiagnoseAmbiguousConversion(Sema &S,
792                                      SourceLocation CaretLoc,
793                                      const PartialDiagnostic &PDiag) const;
794 
795     void dump() const;
796   };
797 
798   enum OverloadFailureKind {
799     ovl_fail_too_many_arguments,
800     ovl_fail_too_few_arguments,
801     ovl_fail_bad_conversion,
802     ovl_fail_bad_deduction,
803 
804     /// This conversion candidate was not considered because it
805     /// duplicates the work of a trivial or derived-to-base
806     /// conversion.
807     ovl_fail_trivial_conversion,
808 
809     /// This conversion candidate was not considered because it is
810     /// an illegal instantiation of a constructor temploid: it is
811     /// callable with one argument, we only have one argument, and
812     /// its first parameter type is exactly the type of the class.
813     ///
814     /// Defining such a constructor directly is illegal, and
815     /// template-argument deduction is supposed to ignore such
816     /// instantiations, but we can still get one with the right
817     /// kind of implicit instantiation.
818     ovl_fail_illegal_constructor,
819 
820     /// This conversion candidate is not viable because its result
821     /// type is not implicitly convertible to the desired type.
822     ovl_fail_bad_final_conversion,
823 
824     /// This conversion function template specialization candidate is not
825     /// viable because the final conversion was not an exact match.
826     ovl_fail_final_conversion_not_exact,
827 
828     /// (CUDA) This candidate was not viable because the callee
829     /// was not accessible from the caller's target (i.e. host->device,
830     /// global->host, device->host).
831     ovl_fail_bad_target,
832 
833     /// This candidate function was not viable because an enable_if
834     /// attribute disabled it.
835     ovl_fail_enable_if,
836 
837     /// This candidate constructor or conversion function is explicit but
838     /// the context doesn't permit explicit functions.
839     ovl_fail_explicit,
840 
841     /// This candidate was not viable because its address could not be taken.
842     ovl_fail_addr_not_available,
843 
844     /// This inherited constructor is not viable because it would slice the
845     /// argument.
846     ovl_fail_inhctor_slice,
847 
848     /// This candidate was not viable because it is a non-default multiversioned
849     /// function.
850     ovl_non_default_multiversion_function,
851 
852     /// This constructor/conversion candidate fail due to an address space
853     /// mismatch between the object being constructed and the overload
854     /// candidate.
855     ovl_fail_object_addrspace_mismatch,
856 
857     /// This candidate was not viable because its associated constraints were
858     /// not satisfied.
859     ovl_fail_constraints_not_satisfied,
860 
861     /// This candidate was not viable because it has internal linkage and is
862     /// from a different module unit than the use.
863     ovl_fail_module_mismatched,
864   };
865 
866   /// A list of implicit conversion sequences for the arguments of an
867   /// OverloadCandidate.
868   using ConversionSequenceList =
869       llvm::MutableArrayRef<ImplicitConversionSequence>;
870 
871   /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
872   struct OverloadCandidate {
873     /// Function - The actual function that this candidate
874     /// represents. When NULL, this is a built-in candidate
875     /// (C++ [over.oper]) or a surrogate for a conversion to a
876     /// function pointer or reference (C++ [over.call.object]).
877     FunctionDecl *Function;
878 
879     /// FoundDecl - The original declaration that was looked up /
880     /// invented / otherwise found, together with its access.
881     /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
882     DeclAccessPair FoundDecl;
883 
884     /// BuiltinParamTypes - Provides the parameter types of a built-in overload
885     /// candidate. Only valid when Function is NULL.
886     QualType BuiltinParamTypes[3];
887 
888     /// Surrogate - The conversion function for which this candidate
889     /// is a surrogate, but only if IsSurrogate is true.
890     CXXConversionDecl *Surrogate;
891 
892     /// The conversion sequences used to convert the function arguments
893     /// to the function parameters. Note that these are indexed by argument,
894     /// so may not match the parameter order of Function.
895     ConversionSequenceList Conversions;
896 
897     /// The FixIt hints which can be used to fix the Bad candidate.
898     ConversionFixItGenerator Fix;
899 
900     /// Viable - True to indicate that this overload candidate is viable.
901     LLVM_PREFERRED_TYPE(bool)
902     unsigned Viable : 1;
903 
904     /// Whether this candidate is the best viable function, or tied for being
905     /// the best viable function.
906     ///
907     /// For an ambiguous overload resolution, indicates whether this candidate
908     /// was part of the ambiguity kernel: the minimal non-empty set of viable
909     /// candidates such that all elements of the ambiguity kernel are better
910     /// than all viable candidates not in the ambiguity kernel.
911     LLVM_PREFERRED_TYPE(bool)
912     unsigned Best : 1;
913 
914     /// IsSurrogate - True to indicate that this candidate is a
915     /// surrogate for a conversion to a function pointer or reference
916     /// (C++ [over.call.object]).
917     LLVM_PREFERRED_TYPE(bool)
918     unsigned IsSurrogate : 1;
919 
920     /// IgnoreObjectArgument - True to indicate that the first
921     /// argument's conversion, which for this function represents the
922     /// implicit object argument, should be ignored. This will be true
923     /// when the candidate is a static member function (where the
924     /// implicit object argument is just a placeholder) or a
925     /// non-static member function when the call doesn't have an
926     /// object argument.
927     LLVM_PREFERRED_TYPE(bool)
928     unsigned IgnoreObjectArgument : 1;
929 
930     LLVM_PREFERRED_TYPE(bool)
931     unsigned TookAddressOfOverload : 1;
932 
933     /// Have we matched any packs on the parameter side, versus any non-packs on
934     /// the argument side, in a context where the opposite matching is also
935     /// allowed?
936     bool HasMatchedPackOnParmToNonPackOnArg : 1;
937 
938     /// True if the candidate was found using ADL.
939     LLVM_PREFERRED_TYPE(CallExpr::ADLCallKind)
940     unsigned IsADLCandidate : 1;
941 
942     /// Whether this is a rewritten candidate, and if so, of what kind?
943     LLVM_PREFERRED_TYPE(OverloadCandidateRewriteKind)
944     unsigned RewriteKind : 2;
945 
946     /// FailureKind - The reason why this candidate is not viable.
947     /// Actually an OverloadFailureKind.
948     unsigned char FailureKind;
949 
950     /// The number of call arguments that were explicitly provided,
951     /// to be used while performing partial ordering of function templates.
952     unsigned ExplicitCallArguments;
953 
954     union {
955       DeductionFailureInfo DeductionFailure;
956 
957       /// FinalConversion - For a conversion function (where Function is
958       /// a CXXConversionDecl), the standard conversion that occurs
959       /// after the call to the overload candidate to convert the result
960       /// of calling the conversion function to the required type.
961       StandardConversionSequence FinalConversion;
962     };
963 
964     /// Get RewriteKind value in OverloadCandidateRewriteKind type (This
965     /// function is to workaround the spurious GCC bitfield enum warning)
966     OverloadCandidateRewriteKind getRewriteKind() const {
967       return static_cast<OverloadCandidateRewriteKind>(RewriteKind);
968     }
969 
970     bool isReversed() const { return getRewriteKind() & CRK_Reversed; }
971 
972     /// hasAmbiguousConversion - Returns whether this overload
973     /// candidate requires an ambiguous conversion or not.
974     bool hasAmbiguousConversion() const {
975       for (auto &C : Conversions) {
976         if (!C.isInitialized()) return false;
977         if (C.isAmbiguous()) return true;
978       }
979       return false;
980     }
981 
982     bool TryToFixBadConversion(unsigned Idx, Sema &S) {
983       bool CanFix = Fix.tryToFixConversion(
984                       Conversions[Idx].Bad.FromExpr,
985                       Conversions[Idx].Bad.getFromType(),
986                       Conversions[Idx].Bad.getToType(), S);
987 
988       // If at least one conversion fails, the candidate cannot be fixed.
989       if (!CanFix)
990         Fix.clear();
991 
992       return CanFix;
993     }
994 
995     unsigned getNumParams() const {
996       if (IsSurrogate) {
997         QualType STy = Surrogate->getConversionType();
998         while (STy->isPointerOrReferenceType())
999           STy = STy->getPointeeType();
1000         return STy->castAs<FunctionProtoType>()->getNumParams();
1001       }
1002       if (Function)
1003         return Function->getNumParams();
1004       return ExplicitCallArguments;
1005     }
1006 
1007     bool NotValidBecauseConstraintExprHasError() const;
1008 
1009   private:
1010     friend class OverloadCandidateSet;
1011     OverloadCandidate()
1012         : IsSurrogate(false), IgnoreObjectArgument(false),
1013           TookAddressOfOverload(false),
1014           HasMatchedPackOnParmToNonPackOnArg(false),
1015           IsADLCandidate(llvm::to_underlying(CallExpr::NotADL)),
1016           RewriteKind(CRK_None) {}
1017   };
1018 
1019   /// OverloadCandidateSet - A set of overload candidates, used in C++
1020   /// overload resolution (C++ 13.3).
1021   class OverloadCandidateSet {
1022   public:
1023     enum CandidateSetKind {
1024       /// Normal lookup.
1025       CSK_Normal,
1026 
1027       /// C++ [over.match.oper]:
1028       /// Lookup of operator function candidates in a call using operator
1029       /// syntax. Candidates that have no parameters of class type will be
1030       /// skipped unless there is a parameter of (reference to) enum type and
1031       /// the corresponding argument is of the same enum type.
1032       CSK_Operator,
1033 
1034       /// C++ [over.match.copy]:
1035       /// Copy-initialization of an object of class type by user-defined
1036       /// conversion.
1037       CSK_InitByUserDefinedConversion,
1038 
1039       /// C++ [over.match.ctor], [over.match.list]
1040       /// Initialization of an object of class type by constructor,
1041       /// using either a parenthesized or braced list of arguments.
1042       CSK_InitByConstructor,
1043 
1044       /// C++ [over.match.call.general]
1045       /// Resolve a call through the address of an overload set.
1046       CSK_AddressOfOverloadSet,
1047     };
1048 
1049     /// Information about operator rewrites to consider when adding operator
1050     /// functions to a candidate set.
1051     struct OperatorRewriteInfo {
1052       OperatorRewriteInfo()
1053           : OriginalOperator(OO_None), OpLoc(), AllowRewrittenCandidates(false) {}
1054       OperatorRewriteInfo(OverloadedOperatorKind Op, SourceLocation OpLoc,
1055                           bool AllowRewritten)
1056           : OriginalOperator(Op), OpLoc(OpLoc),
1057             AllowRewrittenCandidates(AllowRewritten) {}
1058 
1059       /// The original operator as written in the source.
1060       OverloadedOperatorKind OriginalOperator;
1061       /// The source location of the operator.
1062       SourceLocation OpLoc;
1063       /// Whether we should include rewritten candidates in the overload set.
1064       bool AllowRewrittenCandidates;
1065 
1066       /// Would use of this function result in a rewrite using a different
1067       /// operator?
1068       bool isRewrittenOperator(const FunctionDecl *FD) {
1069         return OriginalOperator &&
1070                FD->getDeclName().getCXXOverloadedOperator() != OriginalOperator;
1071       }
1072 
1073       bool isAcceptableCandidate(const FunctionDecl *FD) {
1074         if (!OriginalOperator)
1075           return true;
1076 
1077         // For an overloaded operator, we can have candidates with a different
1078         // name in our unqualified lookup set. Make sure we only consider the
1079         // ones we're supposed to.
1080         OverloadedOperatorKind OO =
1081             FD->getDeclName().getCXXOverloadedOperator();
1082         return OO && (OO == OriginalOperator ||
1083                       (AllowRewrittenCandidates &&
1084                        OO == getRewrittenOverloadedOperator(OriginalOperator)));
1085       }
1086 
1087       /// Determine the kind of rewrite that should be performed for this
1088       /// candidate.
1089       OverloadCandidateRewriteKind
1090       getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO) {
1091         OverloadCandidateRewriteKind CRK = CRK_None;
1092         if (isRewrittenOperator(FD))
1093           CRK = OverloadCandidateRewriteKind(CRK | CRK_DifferentOperator);
1094         if (PO == OverloadCandidateParamOrder::Reversed)
1095           CRK = OverloadCandidateRewriteKind(CRK | CRK_Reversed);
1096         return CRK;
1097       }
1098       /// Determines whether this operator could be implemented by a function
1099       /// with reversed parameter order.
1100       bool isReversible() {
1101         return AllowRewrittenCandidates && OriginalOperator &&
1102                (getRewrittenOverloadedOperator(OriginalOperator) != OO_None ||
1103                 allowsReversed(OriginalOperator));
1104       }
1105 
1106       /// Determine whether reversing parameter order is allowed for operator
1107       /// Op.
1108       bool allowsReversed(OverloadedOperatorKind Op);
1109 
1110       /// Determine whether we should add a rewritten candidate for \p FD with
1111       /// reversed parameter order.
1112       /// \param OriginalArgs are the original non reversed arguments.
1113       bool shouldAddReversed(Sema &S, ArrayRef<Expr *> OriginalArgs,
1114                              FunctionDecl *FD);
1115     };
1116 
1117   private:
1118     SmallVector<OverloadCandidate, 16> Candidates;
1119     llvm::SmallPtrSet<uintptr_t, 16> Functions;
1120 
1121     // Allocator for ConversionSequenceLists. We store the first few of these
1122     // inline to avoid allocation for small sets.
1123     llvm::BumpPtrAllocator SlabAllocator;
1124 
1125     SourceLocation Loc;
1126     CandidateSetKind Kind;
1127     OperatorRewriteInfo RewriteInfo;
1128 
1129     constexpr static unsigned NumInlineBytes =
1130         24 * sizeof(ImplicitConversionSequence);
1131     unsigned NumInlineBytesUsed = 0;
1132     alignas(void *) char InlineSpace[NumInlineBytes];
1133 
1134     // Address space of the object being constructed.
1135     LangAS DestAS = LangAS::Default;
1136 
1137     /// If we have space, allocates from inline storage. Otherwise, allocates
1138     /// from the slab allocator.
1139     /// FIXME: It would probably be nice to have a SmallBumpPtrAllocator
1140     /// instead.
1141     /// FIXME: Now that this only allocates ImplicitConversionSequences, do we
1142     /// want to un-generalize this?
1143     template <typename T>
1144     T *slabAllocate(unsigned N) {
1145       // It's simpler if this doesn't need to consider alignment.
1146       static_assert(alignof(T) == alignof(void *),
1147                     "Only works for pointer-aligned types.");
1148       static_assert(std::is_trivial<T>::value ||
1149                         std::is_same<ImplicitConversionSequence, T>::value,
1150                     "Add destruction logic to OverloadCandidateSet::clear().");
1151 
1152       unsigned NBytes = sizeof(T) * N;
1153       if (NBytes > NumInlineBytes - NumInlineBytesUsed)
1154         return SlabAllocator.Allocate<T>(N);
1155       char *FreeSpaceStart = InlineSpace + NumInlineBytesUsed;
1156       assert(uintptr_t(FreeSpaceStart) % alignof(void *) == 0 &&
1157              "Misaligned storage!");
1158 
1159       NumInlineBytesUsed += NBytes;
1160       return reinterpret_cast<T *>(FreeSpaceStart);
1161     }
1162 
1163     void destroyCandidates();
1164 
1165   public:
1166     OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK,
1167                          OperatorRewriteInfo RewriteInfo = {})
1168         : Loc(Loc), Kind(CSK), RewriteInfo(RewriteInfo) {}
1169     OverloadCandidateSet(const OverloadCandidateSet &) = delete;
1170     OverloadCandidateSet &operator=(const OverloadCandidateSet &) = delete;
1171     ~OverloadCandidateSet() { destroyCandidates(); }
1172 
1173     SourceLocation getLocation() const { return Loc; }
1174     CandidateSetKind getKind() const { return Kind; }
1175     OperatorRewriteInfo getRewriteInfo() const { return RewriteInfo; }
1176 
1177     /// Whether diagnostics should be deferred.
1178     bool shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, SourceLocation OpLoc);
1179 
1180     /// Determine when this overload candidate will be new to the
1181     /// overload set.
1182     bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO =
1183                                      OverloadCandidateParamOrder::Normal) {
1184       uintptr_t Key = reinterpret_cast<uintptr_t>(F->getCanonicalDecl());
1185       Key |= static_cast<uintptr_t>(PO);
1186       return Functions.insert(Key).second;
1187     }
1188 
1189     /// Exclude a function from being considered by overload resolution.
1190     void exclude(Decl *F) {
1191       isNewCandidate(F, OverloadCandidateParamOrder::Normal);
1192       isNewCandidate(F, OverloadCandidateParamOrder::Reversed);
1193     }
1194 
1195     /// Clear out all of the candidates.
1196     void clear(CandidateSetKind CSK);
1197 
1198     using iterator = SmallVectorImpl<OverloadCandidate>::iterator;
1199 
1200     iterator begin() { return Candidates.begin(); }
1201     iterator end() { return Candidates.end(); }
1202 
1203     size_t size() const { return Candidates.size(); }
1204     bool empty() const { return Candidates.empty(); }
1205 
1206     /// Allocate storage for conversion sequences for NumConversions
1207     /// conversions.
1208     ConversionSequenceList
1209     allocateConversionSequences(unsigned NumConversions) {
1210       ImplicitConversionSequence *Conversions =
1211           slabAllocate<ImplicitConversionSequence>(NumConversions);
1212 
1213       // Construct the new objects.
1214       for (unsigned I = 0; I != NumConversions; ++I)
1215         new (&Conversions[I]) ImplicitConversionSequence();
1216 
1217       return ConversionSequenceList(Conversions, NumConversions);
1218     }
1219 
1220     /// Add a new candidate with NumConversions conversion sequence slots
1221     /// to the overload set.
1222     OverloadCandidate &addCandidate(unsigned NumConversions = 0,
1223                                     ConversionSequenceList Conversions = {}) {
1224       assert((Conversions.empty() || Conversions.size() == NumConversions) &&
1225              "preallocated conversion sequence has wrong length");
1226 
1227       Candidates.push_back(OverloadCandidate());
1228       OverloadCandidate &C = Candidates.back();
1229       C.Conversions = Conversions.empty()
1230                           ? allocateConversionSequences(NumConversions)
1231                           : Conversions;
1232       return C;
1233     }
1234 
1235     /// Find the best viable function on this overload set, if it exists.
1236     OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
1237                                          OverloadCandidateSet::iterator& Best);
1238 
1239     SmallVector<OverloadCandidate *, 32> CompleteCandidates(
1240         Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
1241         SourceLocation OpLoc = SourceLocation(),
1242         llvm::function_ref<bool(OverloadCandidate &)> Filter =
1243             [](OverloadCandidate &) { return true; });
1244 
1245     void NoteCandidates(
1246         PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD,
1247         ArrayRef<Expr *> Args, StringRef Opc = "",
1248         SourceLocation Loc = SourceLocation(),
1249         llvm::function_ref<bool(OverloadCandidate &)> Filter =
1250             [](OverloadCandidate &) { return true; });
1251 
1252     void NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
1253                         ArrayRef<OverloadCandidate *> Cands,
1254                         StringRef Opc = "",
1255                         SourceLocation OpLoc = SourceLocation());
1256 
1257     LangAS getDestAS() { return DestAS; }
1258 
1259     void setDestAS(LangAS AS) {
1260       assert((Kind == CSK_InitByConstructor ||
1261               Kind == CSK_InitByUserDefinedConversion) &&
1262              "can't set the destination address space when not constructing an "
1263              "object");
1264       DestAS = AS;
1265     }
1266 
1267   };
1268 
1269   bool isBetterOverloadCandidate(Sema &S,
1270                                  const OverloadCandidate &Cand1,
1271                                  const OverloadCandidate &Cand2,
1272                                  SourceLocation Loc,
1273                                  OverloadCandidateSet::CandidateSetKind Kind);
1274 
1275   struct ConstructorInfo {
1276     DeclAccessPair FoundDecl;
1277     CXXConstructorDecl *Constructor;
1278     FunctionTemplateDecl *ConstructorTmpl;
1279 
1280     explicit operator bool() const { return Constructor; }
1281   };
1282 
1283   // FIXME: Add an AddOverloadCandidate / AddTemplateOverloadCandidate overload
1284   // that takes one of these.
1285   inline ConstructorInfo getConstructorInfo(NamedDecl *ND) {
1286     if (isa<UsingDecl>(ND))
1287       return ConstructorInfo{};
1288 
1289     // For constructors, the access check is performed against the underlying
1290     // declaration, not the found declaration.
1291     auto *D = ND->getUnderlyingDecl();
1292     ConstructorInfo Info = {DeclAccessPair::make(ND, D->getAccess()), nullptr,
1293                             nullptr};
1294     Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
1295     if (Info.ConstructorTmpl)
1296       D = Info.ConstructorTmpl->getTemplatedDecl();
1297     Info.Constructor = dyn_cast<CXXConstructorDecl>(D);
1298     return Info;
1299   }
1300 
1301   // Returns false if signature help is relevant despite number of arguments
1302   // exceeding parameters. Specifically, it returns false when
1303   // PartialOverloading is true and one of the following:
1304   // * Function is variadic
1305   // * Function is template variadic
1306   // * Function is an instantiation of template variadic function
1307   // The last case may seem strange. The idea is that if we added one more
1308   // argument, we'd end up with a function similar to Function. Since, in the
1309   // context of signature help and/or code completion, we do not know what the
1310   // type of the next argument (that the user is typing) will be, this is as
1311   // good candidate as we can get, despite the fact that it takes one less
1312   // parameter.
1313   bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function);
1314 
1315 } // namespace clang
1316 
1317 #endif // LLVM_CLANG_SEMA_OVERLOAD_H
1318