xref: /freebsd/contrib/llvm-project/clang/include/clang/Sema/Overload.h (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
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     /// Whether the source expression was originally a single element
364     /// braced-init-list. Such a conversion is not a perfect match,
365     /// as we prefer a std::initializer_list constructor over an exact match
366     /// constructor.
367     LLVM_PREFERRED_TYPE(bool)
368     unsigned FromBracedInitList : 1;
369 
370     /// FromType - The type that this conversion is converting
371     /// from. This is an opaque pointer that can be translated into a
372     /// QualType.
373     void *FromTypePtr;
374 
375     /// ToType - The types that this conversion is converting to in
376     /// each step. This is an opaque pointer that can be translated
377     /// into a QualType.
378     void *ToTypePtrs[3];
379 
380     /// CopyConstructor - The copy constructor that is used to perform
381     /// this conversion, when the conversion is actually just the
382     /// initialization of an object via copy constructor. Such
383     /// conversions are either identity conversions or derived-to-base
384     /// conversions.
385     CXXConstructorDecl *CopyConstructor;
386     DeclAccessPair FoundCopyConstructor;
387 
setFromType(QualType T)388     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
389 
setToType(unsigned Idx,QualType T)390     void setToType(unsigned Idx, QualType T) {
391       assert(Idx < 3 && "To type index is out of range");
392       ToTypePtrs[Idx] = T.getAsOpaquePtr();
393     }
394 
setAllToTypes(QualType T)395     void setAllToTypes(QualType T) {
396       ToTypePtrs[0] = T.getAsOpaquePtr();
397       ToTypePtrs[1] = ToTypePtrs[0];
398       ToTypePtrs[2] = ToTypePtrs[0];
399     }
400 
getFromType()401     QualType getFromType() const {
402       return QualType::getFromOpaquePtr(FromTypePtr);
403     }
404 
getToType(unsigned Idx)405     QualType getToType(unsigned Idx) const {
406       assert(Idx < 3 && "To type index is out of range");
407       return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
408     }
409 
410     void setAsIdentityConversion();
411 
isIdentityConversion()412     bool isIdentityConversion() const {
413       return Second == ICK_Identity && Dimension == ICK_Identity &&
414              Third == ICK_Identity;
415     }
416 
417     /// A conversion sequence is perfect if it is an identity conversion and
418     /// the type of the source is the same as the type of the target.
isPerfect(const ASTContext & C)419     bool isPerfect(const ASTContext &C) const {
420       if (!isIdentityConversion())
421         return false;
422 
423       // We might prefer a std::initializer_list constructor,
424       // so this sequence cannot be perfect
425       if (FromBracedInitList)
426         return false;
427 
428       // If we are not performing a reference binding, we can skip comparing
429       // the types, which has a noticeable performance impact.
430       if (!ReferenceBinding) {
431 #ifndef NDEBUG
432         auto Decay = [&](QualType T) {
433           if (T->isArrayType() || T->isFunctionType())
434             T = C.getDecayedType(T);
435 
436           // A function pointer type can be resolved to a member function type,
437           // which is still an identity conversion.
438           if (auto *N = T->getAs<MemberPointerType>();
439               N && N->isMemberFunctionPointer())
440             T = C.getDecayedType(N->getPointeeType());
441           return T;
442         };
443         // The types might differ if there is an array-to-pointer conversion
444         // an function-to-pointer conversion, or lvalue-to-rvalue conversion.
445         // In some cases, this may happen even if First is not set.
446         assert(C.hasSameUnqualifiedType(Decay(getFromType()),
447                                         Decay(getToType(2))));
448 #endif
449         return true;
450       }
451       if (!C.hasSameType(getFromType(), getToType(2)))
452         return false;
453       if (BindsToRvalue && IsLvalueReference)
454         return false;
455       return true;
456     }
457 
458     ImplicitConversionRank getRank() const;
459     NarrowingKind
460     getNarrowingKind(ASTContext &Context, const Expr *Converted,
461                      APValue &ConstantValue, QualType &ConstantType,
462                      bool IgnoreFloatToIntegralConversion = false) const;
463     bool isPointerConversionToBool() const;
464     bool isPointerConversionToVoidPointer(ASTContext& Context) const;
465     void dump() const;
466   };
467 
468   /// UserDefinedConversionSequence - Represents a user-defined
469   /// conversion sequence (C++ 13.3.3.1.2).
470   struct UserDefinedConversionSequence {
471     /// Represents the standard conversion that occurs before
472     /// the actual user-defined conversion.
473     ///
474     /// C++11 13.3.3.1.2p1:
475     ///   If the user-defined conversion is specified by a constructor
476     ///   (12.3.1), the initial standard conversion sequence converts
477     ///   the source type to the type required by the argument of the
478     ///   constructor. If the user-defined conversion is specified by
479     ///   a conversion function (12.3.2), the initial standard
480     ///   conversion sequence converts the source type to the implicit
481     ///   object parameter of the conversion function.
482     StandardConversionSequence Before;
483 
484     /// EllipsisConversion - When this is true, it means user-defined
485     /// conversion sequence starts with a ... (ellipsis) conversion, instead of
486     /// a standard conversion. In this case, 'Before' field must be ignored.
487     // FIXME. I much rather put this as the first field. But there seems to be
488     // a gcc code gen. bug which causes a crash in a test. Putting it here seems
489     // to work around the crash.
490     bool EllipsisConversion : 1;
491 
492     /// HadMultipleCandidates - When this is true, it means that the
493     /// conversion function was resolved from an overloaded set having
494     /// size greater than 1.
495     bool HadMultipleCandidates : 1;
496 
497     /// After - Represents the standard conversion that occurs after
498     /// the actual user-defined conversion.
499     StandardConversionSequence After;
500 
501     /// ConversionFunction - The function that will perform the
502     /// user-defined conversion. Null if the conversion is an
503     /// aggregate initialization from an initializer list.
504     FunctionDecl* ConversionFunction;
505 
506     /// The declaration that we found via name lookup, which might be
507     /// the same as \c ConversionFunction or it might be a using declaration
508     /// that refers to \c ConversionFunction.
509     DeclAccessPair FoundConversionFunction;
510 
511     void dump() const;
512   };
513 
514   /// Represents an ambiguous user-defined conversion sequence.
515   struct AmbiguousConversionSequence {
516     using ConversionSet =
517         SmallVector<std::pair<NamedDecl *, FunctionDecl *>, 4>;
518 
519     void *FromTypePtr;
520     void *ToTypePtr;
521     char Buffer[sizeof(ConversionSet)];
522 
getFromTypeAmbiguousConversionSequence523     QualType getFromType() const {
524       return QualType::getFromOpaquePtr(FromTypePtr);
525     }
526 
getToTypeAmbiguousConversionSequence527     QualType getToType() const {
528       return QualType::getFromOpaquePtr(ToTypePtr);
529     }
530 
setFromTypeAmbiguousConversionSequence531     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
setToTypeAmbiguousConversionSequence532     void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
533 
conversionsAmbiguousConversionSequence534     ConversionSet &conversions() {
535       return *reinterpret_cast<ConversionSet*>(Buffer);
536     }
537 
conversionsAmbiguousConversionSequence538     const ConversionSet &conversions() const {
539       return *reinterpret_cast<const ConversionSet*>(Buffer);
540     }
541 
addConversionAmbiguousConversionSequence542     void addConversion(NamedDecl *Found, FunctionDecl *D) {
543       conversions().push_back(std::make_pair(Found, D));
544     }
545 
546     using iterator = ConversionSet::iterator;
547 
beginAmbiguousConversionSequence548     iterator begin() { return conversions().begin(); }
endAmbiguousConversionSequence549     iterator end() { return conversions().end(); }
550 
551     using const_iterator = ConversionSet::const_iterator;
552 
beginAmbiguousConversionSequence553     const_iterator begin() const { return conversions().begin(); }
endAmbiguousConversionSequence554     const_iterator end() const { return conversions().end(); }
555 
556     void construct();
557     void destruct();
558     void copyFrom(const AmbiguousConversionSequence &);
559   };
560 
561   /// BadConversionSequence - Records information about an invalid
562   /// conversion sequence.
563   struct BadConversionSequence {
564     enum FailureKind {
565       no_conversion,
566       unrelated_class,
567       bad_qualifiers,
568       lvalue_ref_to_rvalue,
569       rvalue_ref_to_lvalue,
570       too_few_initializers,
571       too_many_initializers,
572     };
573 
574     // This can be null, e.g. for implicit object arguments.
575     Expr *FromExpr;
576 
577     FailureKind Kind;
578 
579   private:
580     // The type we're converting from (an opaque QualType).
581     void *FromTy;
582 
583     // The type we're converting to (an opaque QualType).
584     void *ToTy;
585 
586   public:
initBadConversionSequence587     void init(FailureKind K, Expr *From, QualType To) {
588       init(K, From->getType(), To);
589       FromExpr = From;
590     }
591 
initBadConversionSequence592     void init(FailureKind K, QualType From, QualType To) {
593       Kind = K;
594       FromExpr = nullptr;
595       setFromType(From);
596       setToType(To);
597     }
598 
getFromTypeBadConversionSequence599     QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
getToTypeBadConversionSequence600     QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
601 
setFromExprBadConversionSequence602     void setFromExpr(Expr *E) {
603       FromExpr = E;
604       setFromType(E->getType());
605     }
606 
setFromTypeBadConversionSequence607     void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
setToTypeBadConversionSequence608     void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
609   };
610 
611   /// ImplicitConversionSequence - Represents an implicit conversion
612   /// sequence, which may be a standard conversion sequence
613   /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
614   /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
615   class ImplicitConversionSequence {
616   public:
617     /// Kind - The kind of implicit conversion sequence. BadConversion
618     /// specifies that there is no conversion from the source type to
619     /// the target type.  AmbiguousConversion represents the unique
620     /// ambiguous conversion (C++0x [over.best.ics]p10).
621     /// StaticObjectArgumentConversion represents the conversion rules for
622     /// the synthesized first argument of calls to static member functions
623     /// ([over.best.ics.general]p8).
624     enum Kind {
625       StandardConversion = 0,
626       StaticObjectArgumentConversion,
627       UserDefinedConversion,
628       AmbiguousConversion,
629       EllipsisConversion,
630       BadConversion
631     };
632 
633   private:
634     enum {
635       Uninitialized = BadConversion + 1
636     };
637 
638     /// ConversionKind - The kind of implicit conversion sequence.
639     LLVM_PREFERRED_TYPE(Kind)
640     unsigned ConversionKind : 31;
641 
642     // Whether the initializer list was of an incomplete array.
643     LLVM_PREFERRED_TYPE(bool)
644     unsigned InitializerListOfIncompleteArray : 1;
645 
646     /// When initializing an array or std::initializer_list from an
647     /// initializer-list, this is the array or std::initializer_list type being
648     /// initialized. The remainder of the conversion sequence, including ToType,
649     /// describe the worst conversion of an initializer to an element of the
650     /// array or std::initializer_list. (Note, 'worst' is not well defined.)
651     QualType InitializerListContainerType;
652 
setKind(Kind K)653     void setKind(Kind K) {
654       destruct();
655       ConversionKind = K;
656     }
657 
destruct()658     void destruct() {
659       if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
660     }
661 
662   public:
663     union {
664       /// When ConversionKind == StandardConversion, provides the
665       /// details of the standard conversion sequence.
666       StandardConversionSequence Standard;
667 
668       /// When ConversionKind == UserDefinedConversion, provides the
669       /// details of the user-defined conversion sequence.
670       UserDefinedConversionSequence UserDefined;
671 
672       /// When ConversionKind == AmbiguousConversion, provides the
673       /// details of the ambiguous conversion.
674       AmbiguousConversionSequence Ambiguous;
675 
676       /// When ConversionKind == BadConversion, provides the details
677       /// of the bad conversion.
678       BadConversionSequence Bad;
679     };
680 
ImplicitConversionSequence()681     ImplicitConversionSequence()
682         : ConversionKind(Uninitialized),
683           InitializerListOfIncompleteArray(false) {
684       Standard.setAsIdentityConversion();
685     }
686 
ImplicitConversionSequence(const ImplicitConversionSequence & Other)687     ImplicitConversionSequence(const ImplicitConversionSequence &Other)
688         : ConversionKind(Other.ConversionKind),
689           InitializerListOfIncompleteArray(
690               Other.InitializerListOfIncompleteArray),
691           InitializerListContainerType(Other.InitializerListContainerType) {
692       switch (ConversionKind) {
693       case Uninitialized: break;
694       case StandardConversion: Standard = Other.Standard; break;
695       case StaticObjectArgumentConversion:
696         break;
697       case UserDefinedConversion: UserDefined = Other.UserDefined; break;
698       case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
699       case EllipsisConversion: break;
700       case BadConversion: Bad = Other.Bad; break;
701       }
702     }
703 
704     ImplicitConversionSequence &
705     operator=(const ImplicitConversionSequence &Other) {
706       destruct();
707       new (this) ImplicitConversionSequence(Other);
708       return *this;
709     }
710 
~ImplicitConversionSequence()711     ~ImplicitConversionSequence() {
712       destruct();
713     }
714 
getKind()715     Kind getKind() const {
716       assert(isInitialized() && "querying uninitialized conversion");
717       return Kind(ConversionKind);
718     }
719 
720     /// Return a ranking of the implicit conversion sequence
721     /// kind, where smaller ranks represent better conversion
722     /// sequences.
723     ///
724     /// In particular, this routine gives user-defined conversion
725     /// sequences and ambiguous conversion sequences the same rank,
726     /// per C++ [over.best.ics]p10.
getKindRank()727     unsigned getKindRank() const {
728       switch (getKind()) {
729       case StandardConversion:
730       case StaticObjectArgumentConversion:
731         return 0;
732 
733       case UserDefinedConversion:
734       case AmbiguousConversion:
735         return 1;
736 
737       case EllipsisConversion:
738         return 2;
739 
740       case BadConversion:
741         return 3;
742       }
743 
744       llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
745     }
746 
isBad()747     bool isBad() const { return getKind() == BadConversion; }
isStandard()748     bool isStandard() const { return getKind() == StandardConversion; }
isStaticObjectArgument()749     bool isStaticObjectArgument() const {
750       return getKind() == StaticObjectArgumentConversion;
751     }
isEllipsis()752     bool isEllipsis() const { return getKind() == EllipsisConversion; }
isAmbiguous()753     bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
isUserDefined()754     bool isUserDefined() const { return getKind() == UserDefinedConversion; }
isFailure()755     bool isFailure() const { return isBad() || isAmbiguous(); }
756 
757     /// Determines whether this conversion sequence has been
758     /// initialized.  Most operations should never need to query
759     /// uninitialized conversions and should assert as above.
isInitialized()760     bool isInitialized() const { return ConversionKind != Uninitialized; }
761 
762     /// Sets this sequence as a bad conversion for an explicit argument.
setBad(BadConversionSequence::FailureKind Failure,Expr * FromExpr,QualType ToType)763     void setBad(BadConversionSequence::FailureKind Failure,
764                 Expr *FromExpr, QualType ToType) {
765       setKind(BadConversion);
766       Bad.init(Failure, FromExpr, ToType);
767     }
768 
769     /// Sets this sequence as a bad conversion for an implicit argument.
setBad(BadConversionSequence::FailureKind Failure,QualType FromType,QualType ToType)770     void setBad(BadConversionSequence::FailureKind Failure,
771                 QualType FromType, QualType ToType) {
772       setKind(BadConversion);
773       Bad.init(Failure, FromType, ToType);
774     }
775 
setStandard()776     void setStandard() { setKind(StandardConversion); }
setStaticObjectArgument()777     void setStaticObjectArgument() { setKind(StaticObjectArgumentConversion); }
setEllipsis()778     void setEllipsis() { setKind(EllipsisConversion); }
setUserDefined()779     void setUserDefined() { setKind(UserDefinedConversion); }
780 
setAmbiguous()781     void setAmbiguous() {
782       if (ConversionKind == AmbiguousConversion) return;
783       ConversionKind = AmbiguousConversion;
784       Ambiguous.construct();
785     }
786 
setAsIdentityConversion(QualType T)787     void setAsIdentityConversion(QualType T) {
788       setStandard();
789       Standard.setAsIdentityConversion();
790       Standard.setFromType(T);
791       Standard.setAllToTypes(T);
792     }
793 
794     /// A conversion sequence is perfect if it is an identity conversion and
795     /// the type of the source is the same as the type of the target.
isPerfect(const ASTContext & C)796     bool isPerfect(const ASTContext &C) const {
797       return isStandard() && Standard.isPerfect(C);
798     }
799 
800     // True iff this is a conversion sequence from an initializer list to an
801     // array or std::initializer.
hasInitializerListContainerType()802     bool hasInitializerListContainerType() const {
803       return !InitializerListContainerType.isNull();
804     }
setInitializerListContainerType(QualType T,bool IA)805     void setInitializerListContainerType(QualType T, bool IA) {
806       InitializerListContainerType = T;
807       InitializerListOfIncompleteArray = IA;
808     }
isInitializerListOfIncompleteArray()809     bool isInitializerListOfIncompleteArray() const {
810       return InitializerListOfIncompleteArray;
811     }
getInitializerListContainerType()812     QualType getInitializerListContainerType() const {
813       assert(hasInitializerListContainerType() &&
814              "not initializer list container");
815       return InitializerListContainerType;
816     }
817 
818     /// Form an "implicit" conversion sequence from nullptr_t to bool, for a
819     /// direct-initialization of a bool object from nullptr_t.
getNullptrToBool(QualType SourceType,QualType DestType,bool NeedLValToRVal)820     static ImplicitConversionSequence getNullptrToBool(QualType SourceType,
821                                                        QualType DestType,
822                                                        bool NeedLValToRVal) {
823       ImplicitConversionSequence ICS;
824       ICS.setStandard();
825       ICS.Standard.setAsIdentityConversion();
826       ICS.Standard.setFromType(SourceType);
827       if (NeedLValToRVal)
828         ICS.Standard.First = ICK_Lvalue_To_Rvalue;
829       ICS.Standard.setToType(0, SourceType);
830       ICS.Standard.Second = ICK_Boolean_Conversion;
831       ICS.Standard.setToType(1, DestType);
832       ICS.Standard.setToType(2, DestType);
833       return ICS;
834     }
835 
836     // The result of a comparison between implicit conversion
837     // sequences. Use Sema::CompareImplicitConversionSequences to
838     // actually perform the comparison.
839     enum CompareKind {
840       Better = -1,
841       Indistinguishable = 0,
842       Worse = 1
843     };
844 
845     void DiagnoseAmbiguousConversion(Sema &S,
846                                      SourceLocation CaretLoc,
847                                      const PartialDiagnostic &PDiag) const;
848 
849     void dump() const;
850   };
851 
852   enum OverloadFailureKind {
853     ovl_fail_too_many_arguments,
854     ovl_fail_too_few_arguments,
855     ovl_fail_bad_conversion,
856     ovl_fail_bad_deduction,
857 
858     /// This conversion candidate was not considered because it
859     /// duplicates the work of a trivial or derived-to-base
860     /// conversion.
861     ovl_fail_trivial_conversion,
862 
863     /// This conversion candidate was not considered because it is
864     /// an illegal instantiation of a constructor temploid: it is
865     /// callable with one argument, we only have one argument, and
866     /// its first parameter type is exactly the type of the class.
867     ///
868     /// Defining such a constructor directly is illegal, and
869     /// template-argument deduction is supposed to ignore such
870     /// instantiations, but we can still get one with the right
871     /// kind of implicit instantiation.
872     ovl_fail_illegal_constructor,
873 
874     /// This conversion candidate is not viable because its result
875     /// type is not implicitly convertible to the desired type.
876     ovl_fail_bad_final_conversion,
877 
878     /// This conversion function template specialization candidate is not
879     /// viable because the final conversion was not an exact match.
880     ovl_fail_final_conversion_not_exact,
881 
882     /// (CUDA) This candidate was not viable because the callee
883     /// was not accessible from the caller's target (i.e. host->device,
884     /// global->host, device->host).
885     ovl_fail_bad_target,
886 
887     /// This candidate function was not viable because an enable_if
888     /// attribute disabled it.
889     ovl_fail_enable_if,
890 
891     /// This candidate constructor or conversion function is explicit but
892     /// the context doesn't permit explicit functions.
893     ovl_fail_explicit,
894 
895     /// This candidate was not viable because its address could not be taken.
896     ovl_fail_addr_not_available,
897 
898     /// This inherited constructor is not viable because it would slice the
899     /// argument.
900     ovl_fail_inhctor_slice,
901 
902     /// This candidate was not viable because it is a non-default multiversioned
903     /// function.
904     ovl_non_default_multiversion_function,
905 
906     /// This constructor/conversion candidate fail due to an address space
907     /// mismatch between the object being constructed and the overload
908     /// candidate.
909     ovl_fail_object_addrspace_mismatch,
910 
911     /// This candidate was not viable because its associated constraints were
912     /// not satisfied.
913     ovl_fail_constraints_not_satisfied,
914 
915     /// This candidate was not viable because it has internal linkage and is
916     /// from a different module unit than the use.
917     ovl_fail_module_mismatched,
918   };
919 
920   /// A list of implicit conversion sequences for the arguments of an
921   /// OverloadCandidate.
922   using ConversionSequenceList =
923       llvm::MutableArrayRef<ImplicitConversionSequence>;
924 
925   /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
926   struct OverloadCandidate {
927     /// Function - The actual function that this candidate
928     /// represents. When NULL, this is a built-in candidate
929     /// (C++ [over.oper]) or a surrogate for a conversion to a
930     /// function pointer or reference (C++ [over.call.object]).
931     FunctionDecl *Function;
932 
933     /// FoundDecl - The original declaration that was looked up /
934     /// invented / otherwise found, together with its access.
935     /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
936     DeclAccessPair FoundDecl;
937 
938     /// BuiltinParamTypes - Provides the parameter types of a built-in overload
939     /// candidate. Only valid when Function is NULL.
940     QualType BuiltinParamTypes[3];
941 
942     /// Surrogate - The conversion function for which this candidate
943     /// is a surrogate, but only if IsSurrogate is true.
944     CXXConversionDecl *Surrogate;
945 
946     /// The conversion sequences used to convert the function arguments
947     /// to the function parameters. Note that these are indexed by argument,
948     /// so may not match the parameter order of Function.
949     ConversionSequenceList Conversions;
950 
951     /// The FixIt hints which can be used to fix the Bad candidate.
952     ConversionFixItGenerator Fix;
953 
954     /// Viable - True to indicate that this overload candidate is viable.
955     LLVM_PREFERRED_TYPE(bool)
956     unsigned Viable : 1;
957 
958     /// Whether this candidate is the best viable function, or tied for being
959     /// the best viable function.
960     ///
961     /// For an ambiguous overload resolution, indicates whether this candidate
962     /// was part of the ambiguity kernel: the minimal non-empty set of viable
963     /// candidates such that all elements of the ambiguity kernel are better
964     /// than all viable candidates not in the ambiguity kernel.
965     LLVM_PREFERRED_TYPE(bool)
966     unsigned Best : 1;
967 
968     /// IsSurrogate - True to indicate that this candidate is a
969     /// surrogate for a conversion to a function pointer or reference
970     /// (C++ [over.call.object]).
971     LLVM_PREFERRED_TYPE(bool)
972     unsigned IsSurrogate : 1;
973 
974     /// IgnoreObjectArgument - True to indicate that the first
975     /// argument's conversion, which for this function represents the
976     /// implicit object argument, should be ignored. This will be true
977     /// when the candidate is a static member function (where the
978     /// implicit object argument is just a placeholder) or a
979     /// non-static member function when the call doesn't have an
980     /// object argument.
981     LLVM_PREFERRED_TYPE(bool)
982     unsigned IgnoreObjectArgument : 1;
983 
984     LLVM_PREFERRED_TYPE(bool)
985     unsigned TookAddressOfOverload : 1;
986 
987     /// Have we matched any packs on the parameter side, versus any non-packs on
988     /// the argument side, in a context where the opposite matching is also
989     /// allowed?
990     LLVM_PREFERRED_TYPE(bool)
991     unsigned StrictPackMatch : 1;
992 
993     /// True if the candidate was found using ADL.
994     LLVM_PREFERRED_TYPE(CallExpr::ADLCallKind)
995     unsigned IsADLCandidate : 1;
996 
997     /// Whether FinalConversion has been set.
998     LLVM_PREFERRED_TYPE(bool)
999     unsigned HasFinalConversion : 1;
1000 
1001     /// Whether this is a rewritten candidate, and if so, of what kind?
1002     LLVM_PREFERRED_TYPE(OverloadCandidateRewriteKind)
1003     unsigned RewriteKind : 2;
1004 
1005     /// FailureKind - The reason why this candidate is not viable.
1006     /// Actually an OverloadFailureKind.
1007     LLVM_PREFERRED_TYPE(OverloadFailureKind)
1008     unsigned FailureKind : 8;
1009 
1010     /// The number of call arguments that were explicitly provided,
1011     /// to be used while performing partial ordering of function templates.
1012     unsigned ExplicitCallArguments;
1013 
1014     union {
1015       DeductionFailureInfo DeductionFailure;
1016 
1017       /// FinalConversion - For a conversion function (where Function is
1018       /// a CXXConversionDecl), the standard conversion that occurs
1019       /// after the call to the overload candidate to convert the result
1020       /// of calling the conversion function to the required type.
1021       StandardConversionSequence FinalConversion;
1022     };
1023 
1024     /// Get RewriteKind value in OverloadCandidateRewriteKind type (This
1025     /// function is to workaround the spurious GCC bitfield enum warning)
getRewriteKindOverloadCandidate1026     OverloadCandidateRewriteKind getRewriteKind() const {
1027       return static_cast<OverloadCandidateRewriteKind>(RewriteKind);
1028     }
1029 
isReversedOverloadCandidate1030     bool isReversed() const { return getRewriteKind() & CRK_Reversed; }
1031 
1032     /// hasAmbiguousConversion - Returns whether this overload
1033     /// candidate requires an ambiguous conversion or not.
hasAmbiguousConversionOverloadCandidate1034     bool hasAmbiguousConversion() const {
1035       for (auto &C : Conversions) {
1036         if (!C.isInitialized()) return false;
1037         if (C.isAmbiguous()) return true;
1038       }
1039       return false;
1040     }
1041 
1042     // An overload is a perfect match if the conversion
1043     // sequences for each argument are perfect.
isPerfectMatchOverloadCandidate1044     bool isPerfectMatch(const ASTContext &Ctx) const {
1045       if (!Viable)
1046         return false;
1047       for (const auto &C : Conversions) {
1048         if (!C.isInitialized() || !C.isPerfect(Ctx))
1049           return false;
1050       }
1051       if (HasFinalConversion)
1052         return FinalConversion.isPerfect(Ctx);
1053       return true;
1054     }
1055 
TryToFixBadConversionOverloadCandidate1056     bool TryToFixBadConversion(unsigned Idx, Sema &S) {
1057       bool CanFix = Fix.tryToFixConversion(
1058                       Conversions[Idx].Bad.FromExpr,
1059                       Conversions[Idx].Bad.getFromType(),
1060                       Conversions[Idx].Bad.getToType(), S);
1061 
1062       // If at least one conversion fails, the candidate cannot be fixed.
1063       if (!CanFix)
1064         Fix.clear();
1065 
1066       return CanFix;
1067     }
1068 
getNumParamsOverloadCandidate1069     unsigned getNumParams() const {
1070       if (IsSurrogate) {
1071         QualType STy = Surrogate->getConversionType();
1072         while (STy->isPointerOrReferenceType())
1073           STy = STy->getPointeeType();
1074         return STy->castAs<FunctionProtoType>()->getNumParams();
1075       }
1076       if (Function)
1077         return Function->getNumParams();
1078       return ExplicitCallArguments;
1079     }
1080 
1081     bool NotValidBecauseConstraintExprHasError() const;
1082 
1083   private:
1084     friend class OverloadCandidateSet;
OverloadCandidateOverloadCandidate1085     OverloadCandidate()
1086         : IsSurrogate(false), IgnoreObjectArgument(false),
1087           TookAddressOfOverload(false), StrictPackMatch(false),
1088           IsADLCandidate(llvm::to_underlying(CallExpr::NotADL)),
1089           HasFinalConversion(false), RewriteKind(CRK_None) {}
1090   };
1091 
1092   struct DeferredTemplateOverloadCandidate {
1093 
1094     // intrusive linked list support for allocateDeferredCandidate
1095     DeferredTemplateOverloadCandidate *Next = nullptr;
1096 
1097     enum Kind { Function, Method, Conversion };
1098 
1099     LLVM_PREFERRED_TYPE(Kind)
1100     unsigned Kind : 2;
1101     LLVM_PREFERRED_TYPE(bool)
1102     unsigned AllowObjCConversionOnExplicit : 1;
1103     LLVM_PREFERRED_TYPE(bool)
1104     unsigned AllowResultConversion : 1;
1105     LLVM_PREFERRED_TYPE(bool)
1106     unsigned AllowExplicit : 1;
1107     LLVM_PREFERRED_TYPE(bool)
1108     unsigned SuppressUserConversions : 1;
1109     LLVM_PREFERRED_TYPE(bool)
1110     unsigned PartialOverloading : 1;
1111     LLVM_PREFERRED_TYPE(bool)
1112     unsigned AggregateCandidateDeduction : 1;
1113   };
1114 
1115   struct DeferredFunctionTemplateOverloadCandidate
1116       : public DeferredTemplateOverloadCandidate {
1117     FunctionTemplateDecl *FunctionTemplate;
1118     DeclAccessPair FoundDecl;
1119     ArrayRef<Expr *> Args;
1120     CallExpr::ADLCallKind IsADLCandidate;
1121     OverloadCandidateParamOrder PO;
1122   };
1123   static_assert(std::is_trivially_destructible_v<
1124                 DeferredFunctionTemplateOverloadCandidate>);
1125 
1126   struct DeferredMethodTemplateOverloadCandidate
1127       : public DeferredTemplateOverloadCandidate {
1128     FunctionTemplateDecl *FunctionTemplate;
1129     DeclAccessPair FoundDecl;
1130     ArrayRef<Expr *> Args;
1131     CXXRecordDecl *ActingContext;
1132     Expr::Classification ObjectClassification;
1133     QualType ObjectType;
1134     OverloadCandidateParamOrder PO;
1135   };
1136   static_assert(std::is_trivially_destructible_v<
1137                 DeferredMethodTemplateOverloadCandidate>);
1138 
1139   struct DeferredConversionTemplateOverloadCandidate
1140       : public DeferredTemplateOverloadCandidate {
1141     FunctionTemplateDecl *FunctionTemplate;
1142     DeclAccessPair FoundDecl;
1143     CXXRecordDecl *ActingContext;
1144     Expr *From;
1145     QualType ToType;
1146   };
1147 
1148   static_assert(std::is_trivially_destructible_v<
1149                 DeferredConversionTemplateOverloadCandidate>);
1150 
1151   /// OverloadCandidateSet - A set of overload candidates, used in C++
1152   /// overload resolution (C++ 13.3).
1153   class OverloadCandidateSet {
1154   public:
1155     enum CandidateSetKind {
1156       /// Normal lookup.
1157       CSK_Normal,
1158 
1159       /// C++ [over.match.oper]:
1160       /// Lookup of operator function candidates in a call using operator
1161       /// syntax. Candidates that have no parameters of class type will be
1162       /// skipped unless there is a parameter of (reference to) enum type and
1163       /// the corresponding argument is of the same enum type.
1164       CSK_Operator,
1165 
1166       /// C++ [over.match.copy]:
1167       /// Copy-initialization of an object of class type by user-defined
1168       /// conversion.
1169       CSK_InitByUserDefinedConversion,
1170 
1171       /// C++ [over.match.ctor], [over.match.list]
1172       /// Initialization of an object of class type by constructor,
1173       /// using either a parenthesized or braced list of arguments.
1174       CSK_InitByConstructor,
1175 
1176       /// C++ [over.match.call.general]
1177       /// Resolve a call through the address of an overload set.
1178       CSK_AddressOfOverloadSet,
1179 
1180       /// When doing overload resolution during code completion,
1181       /// we want to show all viable candidates, including otherwise
1182       /// deferred template candidates.
1183       CSK_CodeCompletion,
1184     };
1185 
1186     /// Information about operator rewrites to consider when adding operator
1187     /// functions to a candidate set.
1188     struct OperatorRewriteInfo {
OperatorRewriteInfoOperatorRewriteInfo1189       OperatorRewriteInfo()
1190           : OriginalOperator(OO_None), OpLoc(), AllowRewrittenCandidates(false) {}
OperatorRewriteInfoOperatorRewriteInfo1191       OperatorRewriteInfo(OverloadedOperatorKind Op, SourceLocation OpLoc,
1192                           bool AllowRewritten)
1193           : OriginalOperator(Op), OpLoc(OpLoc),
1194             AllowRewrittenCandidates(AllowRewritten) {}
1195 
1196       /// The original operator as written in the source.
1197       OverloadedOperatorKind OriginalOperator;
1198       /// The source location of the operator.
1199       SourceLocation OpLoc;
1200       /// Whether we should include rewritten candidates in the overload set.
1201       bool AllowRewrittenCandidates;
1202 
1203       /// Would use of this function result in a rewrite using a different
1204       /// operator?
isRewrittenOperatorOperatorRewriteInfo1205       bool isRewrittenOperator(const FunctionDecl *FD) {
1206         return OriginalOperator &&
1207                FD->getDeclName().getCXXOverloadedOperator() != OriginalOperator;
1208       }
1209 
isAcceptableCandidateOperatorRewriteInfo1210       bool isAcceptableCandidate(const FunctionDecl *FD) {
1211         if (!OriginalOperator)
1212           return true;
1213 
1214         // For an overloaded operator, we can have candidates with a different
1215         // name in our unqualified lookup set. Make sure we only consider the
1216         // ones we're supposed to.
1217         OverloadedOperatorKind OO =
1218             FD->getDeclName().getCXXOverloadedOperator();
1219         return OO && (OO == OriginalOperator ||
1220                       (AllowRewrittenCandidates &&
1221                        OO == getRewrittenOverloadedOperator(OriginalOperator)));
1222       }
1223 
1224       /// Determine the kind of rewrite that should be performed for this
1225       /// candidate.
1226       OverloadCandidateRewriteKind
getRewriteKindOperatorRewriteInfo1227       getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO) {
1228         OverloadCandidateRewriteKind CRK = CRK_None;
1229         if (isRewrittenOperator(FD))
1230           CRK = OverloadCandidateRewriteKind(CRK | CRK_DifferentOperator);
1231         if (PO == OverloadCandidateParamOrder::Reversed)
1232           CRK = OverloadCandidateRewriteKind(CRK | CRK_Reversed);
1233         return CRK;
1234       }
1235       /// Determines whether this operator could be implemented by a function
1236       /// with reversed parameter order.
isReversibleOperatorRewriteInfo1237       bool isReversible() {
1238         return AllowRewrittenCandidates && OriginalOperator &&
1239                (getRewrittenOverloadedOperator(OriginalOperator) != OO_None ||
1240                 allowsReversed(OriginalOperator));
1241       }
1242 
1243       /// Determine whether reversing parameter order is allowed for operator
1244       /// Op.
1245       bool allowsReversed(OverloadedOperatorKind Op);
1246 
1247       /// Determine whether we should add a rewritten candidate for \p FD with
1248       /// reversed parameter order.
1249       /// \param OriginalArgs are the original non reversed arguments.
1250       bool shouldAddReversed(Sema &S, ArrayRef<Expr *> OriginalArgs,
1251                              FunctionDecl *FD);
1252     };
1253 
1254   private:
1255     SmallVector<OverloadCandidate, 16> Candidates;
1256     llvm::SmallPtrSet<uintptr_t, 16> Functions;
1257 
1258     DeferredTemplateOverloadCandidate *FirstDeferredCandidate = nullptr;
1259     unsigned DeferredCandidatesCount : 8 * sizeof(unsigned) - 2;
1260     LLVM_PREFERRED_TYPE(bool)
1261     unsigned HasDeferredTemplateConstructors : 1;
1262     LLVM_PREFERRED_TYPE(bool)
1263     unsigned ResolutionByPerfectCandidateIsDisabled : 1;
1264 
1265     // Allocator for ConversionSequenceLists and deferred candidate args.
1266     // We store the first few of these
1267     // inline to avoid allocation for small sets.
1268     llvm::BumpPtrAllocator SlabAllocator;
1269 
1270     SourceLocation Loc;
1271     CandidateSetKind Kind;
1272     OperatorRewriteInfo RewriteInfo;
1273 
1274     /// Small storage size for ImplicitConversionSequences
1275     /// and the persisted arguments of deferred candidates.
1276     constexpr static unsigned NumInlineBytes =
1277         32 * sizeof(ImplicitConversionSequence);
1278 
1279     unsigned NumInlineBytesUsed = 0;
1280     alignas(void *) char InlineSpace[NumInlineBytes];
1281 
1282     // Address space of the object being constructed.
1283     LangAS DestAS = LangAS::Default;
1284 
1285     /// If we have space, allocates from inline storage. Otherwise, allocates
1286     /// from the slab allocator.
1287     /// FIXME: It would probably be nice to have a SmallBumpPtrAllocator
1288     /// instead.
1289     template <typename T>
slabAllocate(unsigned N)1290     T *slabAllocate(unsigned N) {
1291       // It's simpler if this doesn't need to consider alignment.
1292       static_assert(alignof(T) == alignof(void *),
1293                     "Only works for pointer-aligned types.");
1294       static_assert(std::is_trivially_destructible_v<T> ||
1295                         (std::is_same_v<ImplicitConversionSequence, T>),
1296                     "Add destruction logic to OverloadCandidateSet::clear().");
1297 
1298       unsigned NBytes = sizeof(T) * N;
1299       if (NBytes > NumInlineBytes - NumInlineBytesUsed)
1300         return SlabAllocator.Allocate<T>(N);
1301       char *FreeSpaceStart = InlineSpace + NumInlineBytesUsed;
1302       assert(uintptr_t(FreeSpaceStart) % alignof(void *) == 0 &&
1303              "Misaligned storage!");
1304 
1305       NumInlineBytesUsed += NBytes;
1306       return reinterpret_cast<T *>(FreeSpaceStart);
1307     }
1308 
1309     // Because the size of OverloadCandidateSet has a noticeable impact on
1310     // performance, we store each deferred template candidate in the slab
1311     // allocator such that deferred candidates are ultimately a singly-linked
1312     // intrusive linked list. This ends up being much more efficient than a
1313     // SmallVector that is empty in the common case.
allocateDeferredCandidate()1314     template <typename T> T *allocateDeferredCandidate() {
1315       T *C = slabAllocate<T>(1);
1316       if (!FirstDeferredCandidate)
1317         FirstDeferredCandidate = C;
1318       else {
1319         auto *F = FirstDeferredCandidate;
1320         while (F->Next)
1321           F = F->Next;
1322         F->Next = C;
1323       }
1324       DeferredCandidatesCount++;
1325       return C;
1326     }
1327 
1328     void destroyCandidates();
1329 
1330   public:
1331     OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK,
1332                          OperatorRewriteInfo RewriteInfo = {})
FirstDeferredCandidate(nullptr)1333         : FirstDeferredCandidate(nullptr), DeferredCandidatesCount(0),
1334           HasDeferredTemplateConstructors(false),
1335           ResolutionByPerfectCandidateIsDisabled(false), Loc(Loc), Kind(CSK),
1336           RewriteInfo(RewriteInfo) {}
1337     OverloadCandidateSet(const OverloadCandidateSet &) = delete;
1338     OverloadCandidateSet &operator=(const OverloadCandidateSet &) = delete;
~OverloadCandidateSet()1339     ~OverloadCandidateSet() { destroyCandidates(); }
1340 
getLocation()1341     SourceLocation getLocation() const { return Loc; }
getKind()1342     CandidateSetKind getKind() const { return Kind; }
getRewriteInfo()1343     OperatorRewriteInfo getRewriteInfo() const { return RewriteInfo; }
1344 
1345     /// Whether diagnostics should be deferred.
1346     bool shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, SourceLocation OpLoc);
1347 
1348     // Whether the resolution of template candidates should be deferred
1349     bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const;
1350 
1351     /// Determine when this overload candidate will be new to the
1352     /// overload set.
1353     bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO =
1354                                      OverloadCandidateParamOrder::Normal) {
1355       uintptr_t Key = reinterpret_cast<uintptr_t>(F->getCanonicalDecl());
1356       Key |= static_cast<uintptr_t>(PO);
1357       return Functions.insert(Key).second;
1358     }
1359 
1360     /// Exclude a function from being considered by overload resolution.
exclude(Decl * F)1361     void exclude(Decl *F) {
1362       isNewCandidate(F, OverloadCandidateParamOrder::Normal);
1363       isNewCandidate(F, OverloadCandidateParamOrder::Reversed);
1364     }
1365 
1366     /// Clear out all of the candidates.
1367     void clear(CandidateSetKind CSK);
1368 
1369     using iterator = SmallVectorImpl<OverloadCandidate>::iterator;
1370 
begin()1371     iterator begin() { return Candidates.begin(); }
end()1372     iterator end() { return Candidates.end(); }
1373 
size()1374     size_t size() const { return Candidates.size() + DeferredCandidatesCount; }
1375 
nonDeferredCandidatesCount()1376     size_t nonDeferredCandidatesCount() const { return Candidates.size(); }
1377 
empty()1378     bool empty() const {
1379       return Candidates.empty() && DeferredCandidatesCount == 0;
1380     }
1381 
1382     /// Allocate storage for conversion sequences for NumConversions
1383     /// conversions.
1384     ConversionSequenceList
allocateConversionSequences(unsigned NumConversions)1385     allocateConversionSequences(unsigned NumConversions) {
1386       ImplicitConversionSequence *Conversions =
1387           slabAllocate<ImplicitConversionSequence>(NumConversions);
1388 
1389       // Construct the new objects.
1390       for (unsigned I = 0; I != NumConversions; ++I)
1391         new (&Conversions[I]) ImplicitConversionSequence();
1392 
1393       return ConversionSequenceList(Conversions, NumConversions);
1394     }
1395 
1396     /// Provide storage for any Expr* arg that must be preserved
1397     /// until deferred template candidates are deduced.
1398     /// Typically this should be used for reversed operator arguments
1399     /// and any time the argument array is transformed while adding
1400     /// a template candidate.
getPersistentArgsArray(unsigned N)1401     llvm::MutableArrayRef<Expr *> getPersistentArgsArray(unsigned N) {
1402       Expr **Exprs = slabAllocate<Expr *>(N);
1403       return llvm::MutableArrayRef<Expr *>(Exprs, N);
1404     }
1405 
1406     template <typename... T>
getPersistentArgsArray(T * ...Exprs)1407     llvm::MutableArrayRef<Expr *> getPersistentArgsArray(T *...Exprs) {
1408       llvm::MutableArrayRef<Expr *> Arr =
1409           getPersistentArgsArray(sizeof...(Exprs));
1410       llvm::copy(std::initializer_list<Expr *>{Exprs...}, Arr.data());
1411       return Arr;
1412     }
1413 
1414     /// Add a new candidate with NumConversions conversion sequence slots
1415     /// to the overload set.
1416     OverloadCandidate &addCandidate(unsigned NumConversions = 0,
1417                                     ConversionSequenceList Conversions = {}) {
1418       assert((Conversions.empty() || Conversions.size() == NumConversions) &&
1419              "preallocated conversion sequence has wrong length");
1420 
1421       Candidates.push_back(OverloadCandidate());
1422       OverloadCandidate &C = Candidates.back();
1423       C.Conversions = Conversions.empty()
1424                           ? allocateConversionSequences(NumConversions)
1425                           : Conversions;
1426       return C;
1427     }
1428 
1429     void AddDeferredTemplateCandidate(
1430         FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
1431         ArrayRef<Expr *> Args, bool SuppressUserConversions,
1432         bool PartialOverloading, bool AllowExplicit,
1433         CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
1434         bool AggregateCandidateDeduction);
1435 
1436     void AddDeferredMethodTemplateCandidate(
1437         FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
1438         CXXRecordDecl *ActingContext, QualType ObjectType,
1439         Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
1440         bool SuppressUserConversions, bool PartialOverloading,
1441         OverloadCandidateParamOrder PO);
1442 
1443     void AddDeferredConversionTemplateCandidate(
1444         FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
1445         CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
1446         bool AllowObjCConversionOnExplicit, bool AllowExplicit,
1447         bool AllowResultConversion);
1448 
1449     void InjectNonDeducedTemplateCandidates(Sema &S);
1450 
DisableResolutionByPerfectCandidate()1451     void DisableResolutionByPerfectCandidate() {
1452       ResolutionByPerfectCandidateIsDisabled = true;
1453     }
1454 
1455     /// Find the best viable function on this overload set, if it exists.
1456     OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
1457                                          OverloadCandidateSet::iterator& Best);
1458 
1459     SmallVector<OverloadCandidate *, 32> CompleteCandidates(
1460         Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
1461         SourceLocation OpLoc = SourceLocation(),
1462         llvm::function_ref<bool(OverloadCandidate &)> Filter =
1463             [](OverloadCandidate &) { return true; });
1464 
1465     void NoteCandidates(
1466         PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD,
1467         ArrayRef<Expr *> Args, StringRef Opc = "",
1468         SourceLocation Loc = SourceLocation(),
1469         llvm::function_ref<bool(OverloadCandidate &)> Filter =
1470             [](OverloadCandidate &) { return true; });
1471 
1472     void NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
1473                         ArrayRef<OverloadCandidate *> Cands,
1474                         StringRef Opc = "",
1475                         SourceLocation OpLoc = SourceLocation());
1476 
getDestAS()1477     LangAS getDestAS() { return DestAS; }
1478 
setDestAS(LangAS AS)1479     void setDestAS(LangAS AS) {
1480       assert((Kind == CSK_InitByConstructor ||
1481               Kind == CSK_InitByUserDefinedConversion) &&
1482              "can't set the destination address space when not constructing an "
1483              "object");
1484       DestAS = AS;
1485     }
1486 
1487   private:
1488     OverloadingResult ResultForBestCandidate(const iterator &Best);
1489     void CudaExcludeWrongSideCandidates(
1490         Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates);
1491     OverloadingResult
1492     BestViableFunctionImpl(Sema &S, SourceLocation Loc,
1493                            OverloadCandidateSet::iterator &Best);
1494     void PerfectViableFunction(Sema &S, SourceLocation Loc,
1495                                OverloadCandidateSet::iterator &Best);
1496   };
1497 
1498   bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
1499                                  const OverloadCandidate &Cand2,
1500                                  SourceLocation Loc,
1501                                  OverloadCandidateSet::CandidateSetKind Kind,
1502                                  bool PartialOverloading = false);
1503 
1504   struct ConstructorInfo {
1505     DeclAccessPair FoundDecl;
1506     CXXConstructorDecl *Constructor;
1507     FunctionTemplateDecl *ConstructorTmpl;
1508 
1509     explicit operator bool() const { return Constructor; }
1510   };
1511 
1512   // FIXME: Add an AddOverloadCandidate / AddTemplateOverloadCandidate overload
1513   // that takes one of these.
getConstructorInfo(NamedDecl * ND)1514   inline ConstructorInfo getConstructorInfo(NamedDecl *ND) {
1515     if (isa<UsingDecl>(ND))
1516       return ConstructorInfo{};
1517 
1518     // For constructors, the access check is performed against the underlying
1519     // declaration, not the found declaration.
1520     auto *D = ND->getUnderlyingDecl();
1521     ConstructorInfo Info = {DeclAccessPair::make(ND, D->getAccess()), nullptr,
1522                             nullptr};
1523     Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
1524     if (Info.ConstructorTmpl)
1525       D = Info.ConstructorTmpl->getTemplatedDecl();
1526     Info.Constructor = dyn_cast<CXXConstructorDecl>(D);
1527     return Info;
1528   }
1529 
1530   // Returns false if signature help is relevant despite number of arguments
1531   // exceeding parameters. Specifically, it returns false when
1532   // PartialOverloading is true and one of the following:
1533   // * Function is variadic
1534   // * Function is template variadic
1535   // * Function is an instantiation of template variadic function
1536   // The last case may seem strange. The idea is that if we added one more
1537   // argument, we'd end up with a function similar to Function. Since, in the
1538   // context of signature help and/or code completion, we do not know what the
1539   // type of the next argument (that the user is typing) will be, this is as
1540   // good candidate as we can get, despite the fact that it takes one less
1541   // parameter.
1542   bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function);
1543 
shouldDeferTemplateArgumentDeduction(const LangOptions & Opts)1544   inline bool OverloadCandidateSet::shouldDeferTemplateArgumentDeduction(
1545       const LangOptions &Opts) const {
1546     return
1547         // For user defined conversion we need to check against different
1548         // combination of CV qualifiers and look at any explicit specifier, so
1549         // always deduce template candidates.
1550         Kind != CSK_InitByUserDefinedConversion
1551         // When doing code completion, we want to see all the
1552         // viable candidates.
1553         && Kind != CSK_CodeCompletion
1554         // CUDA may prefer template candidates even when a non-candidate
1555         // is a perfect match
1556         && !Opts.CUDA;
1557   }
1558 
1559 } // namespace clang
1560 
1561 #endif // LLVM_CLANG_SEMA_OVERLOAD_H
1562