• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringRef.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     /// A vector splat from an arithmetic type
166     ICK_Vector_Splat,
167 
168     /// Complex-real conversions (C99 6.3.1.7)
169     ICK_Complex_Real,
170 
171     /// Block Pointer conversions
172     ICK_Block_Pointer_Conversion,
173 
174     /// Transparent Union Conversions
175     ICK_TransparentUnionConversion,
176 
177     /// Objective-C ARC writeback conversion
178     ICK_Writeback_Conversion,
179 
180     /// Zero constant to event (OpenCL1.2 6.12.10)
181     ICK_Zero_Event_Conversion,
182 
183     /// Zero constant to queue
184     ICK_Zero_Queue_Conversion,
185 
186     /// Conversions allowed in C, but not C++
187     ICK_C_Only_Conversion,
188 
189     /// C-only conversion between pointers with incompatible types
190     ICK_Incompatible_Pointer_Conversion,
191 
192     /// The number of conversion kinds
193     ICK_Num_Conversion_Kinds,
194   };
195 
196   /// ImplicitConversionRank - The rank of an implicit conversion
197   /// kind. The enumerator values match with Table 9 of (C++
198   /// 13.3.3.1.1) and are listed such that better conversion ranks
199   /// have smaller values.
200   enum ImplicitConversionRank {
201     /// Exact Match
202     ICR_Exact_Match = 0,
203 
204     /// Promotion
205     ICR_Promotion,
206 
207     /// Conversion
208     ICR_Conversion,
209 
210     /// OpenCL Scalar Widening
211     ICR_OCL_Scalar_Widening,
212 
213     /// Complex <-> Real conversion
214     ICR_Complex_Real_Conversion,
215 
216     /// ObjC ARC writeback conversion
217     ICR_Writeback_Conversion,
218 
219     /// Conversion only allowed in the C standard (e.g. void* to char*).
220     ICR_C_Conversion,
221 
222     /// Conversion not allowed by the C standard, but that we accept as an
223     /// extension anyway.
224     ICR_C_Conversion_Extension
225   };
226 
227   ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
228 
229   /// NarrowingKind - The kind of narrowing conversion being performed by a
230   /// standard conversion sequence according to C++11 [dcl.init.list]p7.
231   enum NarrowingKind {
232     /// Not a narrowing conversion.
233     NK_Not_Narrowing,
234 
235     /// A narrowing conversion by virtue of the source and destination types.
236     NK_Type_Narrowing,
237 
238     /// A narrowing conversion, because a constant expression got narrowed.
239     NK_Constant_Narrowing,
240 
241     /// A narrowing conversion, because a non-constant-expression variable might
242     /// have got narrowed.
243     NK_Variable_Narrowing,
244 
245     /// Cannot tell whether this is a narrowing conversion because the
246     /// expression is value-dependent.
247     NK_Dependent_Narrowing,
248   };
249 
250   /// StandardConversionSequence - represents a standard conversion
251   /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
252   /// contains between zero and three conversions. If a particular
253   /// conversion is not needed, it will be set to the identity conversion
254   /// (ICK_Identity). Note that the three conversions are
255   /// specified as separate members (rather than in an array) so that
256   /// we can keep the size of a standard conversion sequence to a
257   /// single word.
258   class StandardConversionSequence {
259   public:
260     /// First -- The first conversion can be an lvalue-to-rvalue
261     /// conversion, array-to-pointer conversion, or
262     /// function-to-pointer conversion.
263     ImplicitConversionKind First : 8;
264 
265     /// Second - The second conversion can be an integral promotion,
266     /// floating point promotion, integral conversion, floating point
267     /// conversion, floating-integral conversion, pointer conversion,
268     /// pointer-to-member conversion, or boolean conversion.
269     ImplicitConversionKind Second : 8;
270 
271     /// Third - The third conversion can be a qualification conversion
272     /// or a function conversion.
273     ImplicitConversionKind Third : 8;
274 
275     /// Whether this is the deprecated conversion of a
276     /// string literal to a pointer to non-const character data
277     /// (C++ 4.2p2).
278     unsigned DeprecatedStringLiteralToCharPtr : 1;
279 
280     /// Whether the qualification conversion involves a change in the
281     /// Objective-C lifetime (for automatic reference counting).
282     unsigned QualificationIncludesObjCLifetime : 1;
283 
284     /// IncompatibleObjC - Whether this is an Objective-C conversion
285     /// that we should warn about (if we actually use it).
286     unsigned IncompatibleObjC : 1;
287 
288     /// ReferenceBinding - True when this is a reference binding
289     /// (C++ [over.ics.ref]).
290     unsigned ReferenceBinding : 1;
291 
292     /// DirectBinding - True when this is a reference binding that is a
293     /// direct binding (C++ [dcl.init.ref]).
294     unsigned DirectBinding : 1;
295 
296     /// Whether this is an lvalue reference binding (otherwise, it's
297     /// an rvalue reference binding).
298     unsigned IsLvalueReference : 1;
299 
300     /// Whether we're binding to a function lvalue.
301     unsigned BindsToFunctionLvalue : 1;
302 
303     /// Whether we're binding to an rvalue.
304     unsigned BindsToRvalue : 1;
305 
306     /// Whether this binds an implicit object argument to a
307     /// non-static member function without a ref-qualifier.
308     unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
309 
310     /// Whether this binds a reference to an object with a different
311     /// Objective-C lifetime qualifier.
312     unsigned ObjCLifetimeConversionBinding : 1;
313 
314     /// FromType - The type that this conversion is converting
315     /// from. This is an opaque pointer that can be translated into a
316     /// QualType.
317     void *FromTypePtr;
318 
319     /// ToType - The types that this conversion is converting to in
320     /// each step. This is an opaque pointer that can be translated
321     /// into a QualType.
322     void *ToTypePtrs[3];
323 
324     /// CopyConstructor - The copy constructor that is used to perform
325     /// this conversion, when the conversion is actually just the
326     /// initialization of an object via copy constructor. Such
327     /// conversions are either identity conversions or derived-to-base
328     /// conversions.
329     CXXConstructorDecl *CopyConstructor;
330     DeclAccessPair FoundCopyConstructor;
331 
setFromType(QualType T)332     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
333 
setToType(unsigned Idx,QualType T)334     void setToType(unsigned Idx, QualType T) {
335       assert(Idx < 3 && "To type index is out of range");
336       ToTypePtrs[Idx] = T.getAsOpaquePtr();
337     }
338 
setAllToTypes(QualType T)339     void setAllToTypes(QualType T) {
340       ToTypePtrs[0] = T.getAsOpaquePtr();
341       ToTypePtrs[1] = ToTypePtrs[0];
342       ToTypePtrs[2] = ToTypePtrs[0];
343     }
344 
getFromType()345     QualType getFromType() const {
346       return QualType::getFromOpaquePtr(FromTypePtr);
347     }
348 
getToType(unsigned Idx)349     QualType getToType(unsigned Idx) const {
350       assert(Idx < 3 && "To type index is out of range");
351       return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
352     }
353 
354     void setAsIdentityConversion();
355 
isIdentityConversion()356     bool isIdentityConversion() const {
357       return Second == ICK_Identity && Third == ICK_Identity;
358     }
359 
360     ImplicitConversionRank getRank() const;
361     NarrowingKind
362     getNarrowingKind(ASTContext &Context, const Expr *Converted,
363                      APValue &ConstantValue, QualType &ConstantType,
364                      bool IgnoreFloatToIntegralConversion = false) const;
365     bool isPointerConversionToBool() const;
366     bool isPointerConversionToVoidPointer(ASTContext& Context) const;
367     void dump() const;
368   };
369 
370   /// UserDefinedConversionSequence - Represents a user-defined
371   /// conversion sequence (C++ 13.3.3.1.2).
372   struct UserDefinedConversionSequence {
373     /// Represents the standard conversion that occurs before
374     /// the actual user-defined conversion.
375     ///
376     /// C++11 13.3.3.1.2p1:
377     ///   If the user-defined conversion is specified by a constructor
378     ///   (12.3.1), the initial standard conversion sequence converts
379     ///   the source type to the type required by the argument of the
380     ///   constructor. If the user-defined conversion is specified by
381     ///   a conversion function (12.3.2), the initial standard
382     ///   conversion sequence converts the source type to the implicit
383     ///   object parameter of the conversion function.
384     StandardConversionSequence Before;
385 
386     /// EllipsisConversion - When this is true, it means user-defined
387     /// conversion sequence starts with a ... (ellipsis) conversion, instead of
388     /// a standard conversion. In this case, 'Before' field must be ignored.
389     // FIXME. I much rather put this as the first field. But there seems to be
390     // a gcc code gen. bug which causes a crash in a test. Putting it here seems
391     // to work around the crash.
392     bool EllipsisConversion : 1;
393 
394     /// HadMultipleCandidates - When this is true, it means that the
395     /// conversion function was resolved from an overloaded set having
396     /// size greater than 1.
397     bool HadMultipleCandidates : 1;
398 
399     /// After - Represents the standard conversion that occurs after
400     /// the actual user-defined conversion.
401     StandardConversionSequence After;
402 
403     /// ConversionFunction - The function that will perform the
404     /// user-defined conversion. Null if the conversion is an
405     /// aggregate initialization from an initializer list.
406     FunctionDecl* ConversionFunction;
407 
408     /// The declaration that we found via name lookup, which might be
409     /// the same as \c ConversionFunction or it might be a using declaration
410     /// that refers to \c ConversionFunction.
411     DeclAccessPair FoundConversionFunction;
412 
413     void dump() const;
414   };
415 
416   /// Represents an ambiguous user-defined conversion sequence.
417   struct AmbiguousConversionSequence {
418     using ConversionSet =
419         SmallVector<std::pair<NamedDecl *, FunctionDecl *>, 4>;
420 
421     void *FromTypePtr;
422     void *ToTypePtr;
423     char Buffer[sizeof(ConversionSet)];
424 
getFromTypeAmbiguousConversionSequence425     QualType getFromType() const {
426       return QualType::getFromOpaquePtr(FromTypePtr);
427     }
428 
getToTypeAmbiguousConversionSequence429     QualType getToType() const {
430       return QualType::getFromOpaquePtr(ToTypePtr);
431     }
432 
setFromTypeAmbiguousConversionSequence433     void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
setToTypeAmbiguousConversionSequence434     void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
435 
conversionsAmbiguousConversionSequence436     ConversionSet &conversions() {
437       return *reinterpret_cast<ConversionSet*>(Buffer);
438     }
439 
conversionsAmbiguousConversionSequence440     const ConversionSet &conversions() const {
441       return *reinterpret_cast<const ConversionSet*>(Buffer);
442     }
443 
addConversionAmbiguousConversionSequence444     void addConversion(NamedDecl *Found, FunctionDecl *D) {
445       conversions().push_back(std::make_pair(Found, D));
446     }
447 
448     using iterator = ConversionSet::iterator;
449 
beginAmbiguousConversionSequence450     iterator begin() { return conversions().begin(); }
endAmbiguousConversionSequence451     iterator end() { return conversions().end(); }
452 
453     using const_iterator = ConversionSet::const_iterator;
454 
beginAmbiguousConversionSequence455     const_iterator begin() const { return conversions().begin(); }
endAmbiguousConversionSequence456     const_iterator end() const { return conversions().end(); }
457 
458     void construct();
459     void destruct();
460     void copyFrom(const AmbiguousConversionSequence &);
461   };
462 
463   /// BadConversionSequence - Records information about an invalid
464   /// conversion sequence.
465   struct BadConversionSequence {
466     enum FailureKind {
467       no_conversion,
468       unrelated_class,
469       bad_qualifiers,
470       lvalue_ref_to_rvalue,
471       rvalue_ref_to_lvalue
472     };
473 
474     // This can be null, e.g. for implicit object arguments.
475     Expr *FromExpr;
476 
477     FailureKind Kind;
478 
479   private:
480     // The type we're converting from (an opaque QualType).
481     void *FromTy;
482 
483     // The type we're converting to (an opaque QualType).
484     void *ToTy;
485 
486   public:
initBadConversionSequence487     void init(FailureKind K, Expr *From, QualType To) {
488       init(K, From->getType(), To);
489       FromExpr = From;
490     }
491 
initBadConversionSequence492     void init(FailureKind K, QualType From, QualType To) {
493       Kind = K;
494       FromExpr = nullptr;
495       setFromType(From);
496       setToType(To);
497     }
498 
getFromTypeBadConversionSequence499     QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
getToTypeBadConversionSequence500     QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
501 
setFromExprBadConversionSequence502     void setFromExpr(Expr *E) {
503       FromExpr = E;
504       setFromType(E->getType());
505     }
506 
setFromTypeBadConversionSequence507     void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
setToTypeBadConversionSequence508     void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
509   };
510 
511   /// ImplicitConversionSequence - Represents an implicit conversion
512   /// sequence, which may be a standard conversion sequence
513   /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
514   /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
515   class ImplicitConversionSequence {
516   public:
517     /// Kind - The kind of implicit conversion sequence. BadConversion
518     /// specifies that there is no conversion from the source type to
519     /// the target type.  AmbiguousConversion represents the unique
520     /// ambiguous conversion (C++0x [over.best.ics]p10).
521     enum Kind {
522       StandardConversion = 0,
523       UserDefinedConversion,
524       AmbiguousConversion,
525       EllipsisConversion,
526       BadConversion
527     };
528 
529   private:
530     enum {
531       Uninitialized = BadConversion + 1
532     };
533 
534     /// ConversionKind - The kind of implicit conversion sequence.
535     unsigned ConversionKind : 30;
536 
537     /// Whether the target is really a std::initializer_list, and the
538     /// sequence only represents the worst element conversion.
539     unsigned StdInitializerListElement : 1;
540 
setKind(Kind K)541     void setKind(Kind K) {
542       destruct();
543       ConversionKind = K;
544     }
545 
destruct()546     void destruct() {
547       if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
548     }
549 
550   public:
551     union {
552       /// When ConversionKind == StandardConversion, provides the
553       /// details of the standard conversion sequence.
554       StandardConversionSequence Standard;
555 
556       /// When ConversionKind == UserDefinedConversion, provides the
557       /// details of the user-defined conversion sequence.
558       UserDefinedConversionSequence UserDefined;
559 
560       /// When ConversionKind == AmbiguousConversion, provides the
561       /// details of the ambiguous conversion.
562       AmbiguousConversionSequence Ambiguous;
563 
564       /// When ConversionKind == BadConversion, provides the details
565       /// of the bad conversion.
566       BadConversionSequence Bad;
567     };
568 
ImplicitConversionSequence()569     ImplicitConversionSequence()
570         : ConversionKind(Uninitialized), StdInitializerListElement(false) {
571       Standard.setAsIdentityConversion();
572     }
573 
ImplicitConversionSequence(const ImplicitConversionSequence & Other)574     ImplicitConversionSequence(const ImplicitConversionSequence &Other)
575         : ConversionKind(Other.ConversionKind),
576           StdInitializerListElement(Other.StdInitializerListElement) {
577       switch (ConversionKind) {
578       case Uninitialized: break;
579       case StandardConversion: Standard = Other.Standard; break;
580       case UserDefinedConversion: UserDefined = Other.UserDefined; break;
581       case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
582       case EllipsisConversion: break;
583       case BadConversion: Bad = Other.Bad; break;
584       }
585     }
586 
587     ImplicitConversionSequence &
588     operator=(const ImplicitConversionSequence &Other) {
589       destruct();
590       new (this) ImplicitConversionSequence(Other);
591       return *this;
592     }
593 
~ImplicitConversionSequence()594     ~ImplicitConversionSequence() {
595       destruct();
596     }
597 
getKind()598     Kind getKind() const {
599       assert(isInitialized() && "querying uninitialized conversion");
600       return Kind(ConversionKind);
601     }
602 
603     /// Return a ranking of the implicit conversion sequence
604     /// kind, where smaller ranks represent better conversion
605     /// sequences.
606     ///
607     /// In particular, this routine gives user-defined conversion
608     /// sequences and ambiguous conversion sequences the same rank,
609     /// per C++ [over.best.ics]p10.
getKindRank()610     unsigned getKindRank() const {
611       switch (getKind()) {
612       case StandardConversion:
613         return 0;
614 
615       case UserDefinedConversion:
616       case AmbiguousConversion:
617         return 1;
618 
619       case EllipsisConversion:
620         return 2;
621 
622       case BadConversion:
623         return 3;
624       }
625 
626       llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
627     }
628 
isBad()629     bool isBad() const { return getKind() == BadConversion; }
isStandard()630     bool isStandard() const { return getKind() == StandardConversion; }
isEllipsis()631     bool isEllipsis() const { return getKind() == EllipsisConversion; }
isAmbiguous()632     bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
isUserDefined()633     bool isUserDefined() const { return getKind() == UserDefinedConversion; }
isFailure()634     bool isFailure() const { return isBad() || isAmbiguous(); }
635 
636     /// Determines whether this conversion sequence has been
637     /// initialized.  Most operations should never need to query
638     /// uninitialized conversions and should assert as above.
isInitialized()639     bool isInitialized() const { return ConversionKind != Uninitialized; }
640 
641     /// Sets this sequence as a bad conversion for an explicit argument.
setBad(BadConversionSequence::FailureKind Failure,Expr * FromExpr,QualType ToType)642     void setBad(BadConversionSequence::FailureKind Failure,
643                 Expr *FromExpr, QualType ToType) {
644       setKind(BadConversion);
645       Bad.init(Failure, FromExpr, ToType);
646     }
647 
648     /// Sets this sequence as a bad conversion for an implicit argument.
setBad(BadConversionSequence::FailureKind Failure,QualType FromType,QualType ToType)649     void setBad(BadConversionSequence::FailureKind Failure,
650                 QualType FromType, QualType ToType) {
651       setKind(BadConversion);
652       Bad.init(Failure, FromType, ToType);
653     }
654 
setStandard()655     void setStandard() { setKind(StandardConversion); }
setEllipsis()656     void setEllipsis() { setKind(EllipsisConversion); }
setUserDefined()657     void setUserDefined() { setKind(UserDefinedConversion); }
658 
setAmbiguous()659     void setAmbiguous() {
660       if (ConversionKind == AmbiguousConversion) return;
661       ConversionKind = AmbiguousConversion;
662       Ambiguous.construct();
663     }
664 
setAsIdentityConversion(QualType T)665     void setAsIdentityConversion(QualType T) {
666       setStandard();
667       Standard.setAsIdentityConversion();
668       Standard.setFromType(T);
669       Standard.setAllToTypes(T);
670     }
671 
672     /// Whether the target is really a std::initializer_list, and the
673     /// sequence only represents the worst element conversion.
isStdInitializerListElement()674     bool isStdInitializerListElement() const {
675       return StdInitializerListElement;
676     }
677 
678     void setStdInitializerListElement(bool V = true) {
679       StdInitializerListElement = V;
680     }
681 
682     /// Form an "implicit" conversion sequence from nullptr_t to bool, for a
683     /// direct-initialization of a bool object from nullptr_t.
getNullptrToBool(QualType SourceType,QualType DestType,bool NeedLValToRVal)684     static ImplicitConversionSequence getNullptrToBool(QualType SourceType,
685                                                        QualType DestType,
686                                                        bool NeedLValToRVal) {
687       ImplicitConversionSequence ICS;
688       ICS.setStandard();
689       ICS.Standard.setAsIdentityConversion();
690       ICS.Standard.setFromType(SourceType);
691       if (NeedLValToRVal)
692         ICS.Standard.First = ICK_Lvalue_To_Rvalue;
693       ICS.Standard.setToType(0, SourceType);
694       ICS.Standard.Second = ICK_Boolean_Conversion;
695       ICS.Standard.setToType(1, DestType);
696       ICS.Standard.setToType(2, DestType);
697       return ICS;
698     }
699 
700     // The result of a comparison between implicit conversion
701     // sequences. Use Sema::CompareImplicitConversionSequences to
702     // actually perform the comparison.
703     enum CompareKind {
704       Better = -1,
705       Indistinguishable = 0,
706       Worse = 1
707     };
708 
709     void DiagnoseAmbiguousConversion(Sema &S,
710                                      SourceLocation CaretLoc,
711                                      const PartialDiagnostic &PDiag) const;
712 
713     void dump() const;
714   };
715 
716   enum OverloadFailureKind {
717     ovl_fail_too_many_arguments,
718     ovl_fail_too_few_arguments,
719     ovl_fail_bad_conversion,
720     ovl_fail_bad_deduction,
721 
722     /// This conversion candidate was not considered because it
723     /// duplicates the work of a trivial or derived-to-base
724     /// conversion.
725     ovl_fail_trivial_conversion,
726 
727     /// This conversion candidate was not considered because it is
728     /// an illegal instantiation of a constructor temploid: it is
729     /// callable with one argument, we only have one argument, and
730     /// its first parameter type is exactly the type of the class.
731     ///
732     /// Defining such a constructor directly is illegal, and
733     /// template-argument deduction is supposed to ignore such
734     /// instantiations, but we can still get one with the right
735     /// kind of implicit instantiation.
736     ovl_fail_illegal_constructor,
737 
738     /// This conversion candidate is not viable because its result
739     /// type is not implicitly convertible to the desired type.
740     ovl_fail_bad_final_conversion,
741 
742     /// This conversion function template specialization candidate is not
743     /// viable because the final conversion was not an exact match.
744     ovl_fail_final_conversion_not_exact,
745 
746     /// (CUDA) This candidate was not viable because the callee
747     /// was not accessible from the caller's target (i.e. host->device,
748     /// global->host, device->host).
749     ovl_fail_bad_target,
750 
751     /// This candidate function was not viable because an enable_if
752     /// attribute disabled it.
753     ovl_fail_enable_if,
754 
755     /// This candidate constructor or conversion function is explicit but
756     /// the context doesn't permit explicit functions.
757     ovl_fail_explicit,
758 
759     /// This candidate was not viable because its address could not be taken.
760     ovl_fail_addr_not_available,
761 
762     /// This candidate was not viable because its OpenCL extension is disabled.
763     ovl_fail_ext_disabled,
764 
765     /// This inherited constructor is not viable because it would slice the
766     /// argument.
767     ovl_fail_inhctor_slice,
768 
769     /// This candidate was not viable because it is a non-default multiversioned
770     /// function.
771     ovl_non_default_multiversion_function,
772 
773     /// This constructor/conversion candidate fail due to an address space
774     /// mismatch between the object being constructed and the overload
775     /// candidate.
776     ovl_fail_object_addrspace_mismatch,
777 
778     /// This candidate was not viable because its associated constraints were
779     /// not satisfied.
780     ovl_fail_constraints_not_satisfied,
781   };
782 
783   /// A list of implicit conversion sequences for the arguments of an
784   /// OverloadCandidate.
785   using ConversionSequenceList =
786       llvm::MutableArrayRef<ImplicitConversionSequence>;
787 
788   /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
789   struct OverloadCandidate {
790     /// Function - The actual function that this candidate
791     /// represents. When NULL, this is a built-in candidate
792     /// (C++ [over.oper]) or a surrogate for a conversion to a
793     /// function pointer or reference (C++ [over.call.object]).
794     FunctionDecl *Function;
795 
796     /// FoundDecl - The original declaration that was looked up /
797     /// invented / otherwise found, together with its access.
798     /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
799     DeclAccessPair FoundDecl;
800 
801     /// BuiltinParamTypes - Provides the parameter types of a built-in overload
802     /// candidate. Only valid when Function is NULL.
803     QualType BuiltinParamTypes[3];
804 
805     /// Surrogate - The conversion function for which this candidate
806     /// is a surrogate, but only if IsSurrogate is true.
807     CXXConversionDecl *Surrogate;
808 
809     /// The conversion sequences used to convert the function arguments
810     /// to the function parameters. Note that these are indexed by argument,
811     /// so may not match the parameter order of Function.
812     ConversionSequenceList Conversions;
813 
814     /// The FixIt hints which can be used to fix the Bad candidate.
815     ConversionFixItGenerator Fix;
816 
817     /// Viable - True to indicate that this overload candidate is viable.
818     bool Viable : 1;
819 
820     /// Whether this candidate is the best viable function, or tied for being
821     /// the best viable function.
822     ///
823     /// For an ambiguous overload resolution, indicates whether this candidate
824     /// was part of the ambiguity kernel: the minimal non-empty set of viable
825     /// candidates such that all elements of the ambiguity kernel are better
826     /// than all viable candidates not in the ambiguity kernel.
827     bool Best : 1;
828 
829     /// IsSurrogate - True to indicate that this candidate is a
830     /// surrogate for a conversion to a function pointer or reference
831     /// (C++ [over.call.object]).
832     bool IsSurrogate : 1;
833 
834     /// IgnoreObjectArgument - True to indicate that the first
835     /// argument's conversion, which for this function represents the
836     /// implicit object argument, should be ignored. This will be true
837     /// when the candidate is a static member function (where the
838     /// implicit object argument is just a placeholder) or a
839     /// non-static member function when the call doesn't have an
840     /// object argument.
841     bool IgnoreObjectArgument : 1;
842 
843     /// True if the candidate was found using ADL.
844     CallExpr::ADLCallKind IsADLCandidate : 1;
845 
846     /// Whether this is a rewritten candidate, and if so, of what kind?
847     unsigned RewriteKind : 2;
848 
849     /// FailureKind - The reason why this candidate is not viable.
850     /// Actually an OverloadFailureKind.
851     unsigned char FailureKind;
852 
853     /// The number of call arguments that were explicitly provided,
854     /// to be used while performing partial ordering of function templates.
855     unsigned ExplicitCallArguments;
856 
857     union {
858       DeductionFailureInfo DeductionFailure;
859 
860       /// FinalConversion - For a conversion function (where Function is
861       /// a CXXConversionDecl), the standard conversion that occurs
862       /// after the call to the overload candidate to convert the result
863       /// of calling the conversion function to the required type.
864       StandardConversionSequence FinalConversion;
865     };
866 
867     /// Get RewriteKind value in OverloadCandidateRewriteKind type (This
868     /// function is to workaround the spurious GCC bitfield enum warning)
getRewriteKindOverloadCandidate869     OverloadCandidateRewriteKind getRewriteKind() const {
870       return static_cast<OverloadCandidateRewriteKind>(RewriteKind);
871     }
872 
isReversedOverloadCandidate873     bool isReversed() const { return getRewriteKind() & CRK_Reversed; }
874 
875     /// hasAmbiguousConversion - Returns whether this overload
876     /// candidate requires an ambiguous conversion or not.
hasAmbiguousConversionOverloadCandidate877     bool hasAmbiguousConversion() const {
878       for (auto &C : Conversions) {
879         if (!C.isInitialized()) return false;
880         if (C.isAmbiguous()) return true;
881       }
882       return false;
883     }
884 
TryToFixBadConversionOverloadCandidate885     bool TryToFixBadConversion(unsigned Idx, Sema &S) {
886       bool CanFix = Fix.tryToFixConversion(
887                       Conversions[Idx].Bad.FromExpr,
888                       Conversions[Idx].Bad.getFromType(),
889                       Conversions[Idx].Bad.getToType(), S);
890 
891       // If at least one conversion fails, the candidate cannot be fixed.
892       if (!CanFix)
893         Fix.clear();
894 
895       return CanFix;
896     }
897 
getNumParamsOverloadCandidate898     unsigned getNumParams() const {
899       if (IsSurrogate) {
900         QualType STy = Surrogate->getConversionType();
901         while (STy->isPointerType() || STy->isReferenceType())
902           STy = STy->getPointeeType();
903         return STy->castAs<FunctionProtoType>()->getNumParams();
904       }
905       if (Function)
906         return Function->getNumParams();
907       return ExplicitCallArguments;
908     }
909 
910   private:
911     friend class OverloadCandidateSet;
OverloadCandidateOverloadCandidate912     OverloadCandidate()
913         : IsSurrogate(false), IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {}
914   };
915 
916   /// OverloadCandidateSet - A set of overload candidates, used in C++
917   /// overload resolution (C++ 13.3).
918   class OverloadCandidateSet {
919   public:
920     enum CandidateSetKind {
921       /// Normal lookup.
922       CSK_Normal,
923 
924       /// C++ [over.match.oper]:
925       /// Lookup of operator function candidates in a call using operator
926       /// syntax. Candidates that have no parameters of class type will be
927       /// skipped unless there is a parameter of (reference to) enum type and
928       /// the corresponding argument is of the same enum type.
929       CSK_Operator,
930 
931       /// C++ [over.match.copy]:
932       /// Copy-initialization of an object of class type by user-defined
933       /// conversion.
934       CSK_InitByUserDefinedConversion,
935 
936       /// C++ [over.match.ctor], [over.match.list]
937       /// Initialization of an object of class type by constructor,
938       /// using either a parenthesized or braced list of arguments.
939       CSK_InitByConstructor,
940     };
941 
942     /// Information about operator rewrites to consider when adding operator
943     /// functions to a candidate set.
944     struct OperatorRewriteInfo {
OperatorRewriteInfoOperatorRewriteInfo945       OperatorRewriteInfo()
946           : OriginalOperator(OO_None), AllowRewrittenCandidates(false) {}
OperatorRewriteInfoOperatorRewriteInfo947       OperatorRewriteInfo(OverloadedOperatorKind Op, bool AllowRewritten)
948           : OriginalOperator(Op), AllowRewrittenCandidates(AllowRewritten) {}
949 
950       /// The original operator as written in the source.
951       OverloadedOperatorKind OriginalOperator;
952       /// Whether we should include rewritten candidates in the overload set.
953       bool AllowRewrittenCandidates;
954 
955       /// Would use of this function result in a rewrite using a different
956       /// operator?
isRewrittenOperatorOperatorRewriteInfo957       bool isRewrittenOperator(const FunctionDecl *FD) {
958         return OriginalOperator &&
959                FD->getDeclName().getCXXOverloadedOperator() != OriginalOperator;
960       }
961 
isAcceptableCandidateOperatorRewriteInfo962       bool isAcceptableCandidate(const FunctionDecl *FD) {
963         if (!OriginalOperator)
964           return true;
965 
966         // For an overloaded operator, we can have candidates with a different
967         // name in our unqualified lookup set. Make sure we only consider the
968         // ones we're supposed to.
969         OverloadedOperatorKind OO =
970             FD->getDeclName().getCXXOverloadedOperator();
971         return OO && (OO == OriginalOperator ||
972                       (AllowRewrittenCandidates &&
973                        OO == getRewrittenOverloadedOperator(OriginalOperator)));
974       }
975 
976       /// Determine the kind of rewrite that should be performed for this
977       /// candidate.
978       OverloadCandidateRewriteKind
getRewriteKindOperatorRewriteInfo979       getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO) {
980         OverloadCandidateRewriteKind CRK = CRK_None;
981         if (isRewrittenOperator(FD))
982           CRK = OverloadCandidateRewriteKind(CRK | CRK_DifferentOperator);
983         if (PO == OverloadCandidateParamOrder::Reversed)
984           CRK = OverloadCandidateRewriteKind(CRK | CRK_Reversed);
985         return CRK;
986       }
987 
988       /// Determines whether this operator could be implemented by a function
989       /// with reversed parameter order.
isReversibleOperatorRewriteInfo990       bool isReversible() {
991         return AllowRewrittenCandidates && OriginalOperator &&
992                (getRewrittenOverloadedOperator(OriginalOperator) != OO_None ||
993                 shouldAddReversed(OriginalOperator));
994       }
995 
996       /// Determine whether we should consider looking for and adding reversed
997       /// candidates for operator Op.
998       bool shouldAddReversed(OverloadedOperatorKind Op);
999 
1000       /// Determine whether we should add a rewritten candidate for \p FD with
1001       /// reversed parameter order.
1002       bool shouldAddReversed(ASTContext &Ctx, const FunctionDecl *FD);
1003     };
1004 
1005   private:
1006     SmallVector<OverloadCandidate, 16> Candidates;
1007     llvm::SmallPtrSet<uintptr_t, 16> Functions;
1008 
1009     // Allocator for ConversionSequenceLists. We store the first few of these
1010     // inline to avoid allocation for small sets.
1011     llvm::BumpPtrAllocator SlabAllocator;
1012 
1013     SourceLocation Loc;
1014     CandidateSetKind Kind;
1015     OperatorRewriteInfo RewriteInfo;
1016 
1017     constexpr static unsigned NumInlineBytes =
1018         24 * sizeof(ImplicitConversionSequence);
1019     unsigned NumInlineBytesUsed = 0;
1020     alignas(void *) char InlineSpace[NumInlineBytes];
1021 
1022     // Address space of the object being constructed.
1023     LangAS DestAS = LangAS::Default;
1024 
1025     /// If we have space, allocates from inline storage. Otherwise, allocates
1026     /// from the slab allocator.
1027     /// FIXME: It would probably be nice to have a SmallBumpPtrAllocator
1028     /// instead.
1029     /// FIXME: Now that this only allocates ImplicitConversionSequences, do we
1030     /// want to un-generalize this?
1031     template <typename T>
slabAllocate(unsigned N)1032     T *slabAllocate(unsigned N) {
1033       // It's simpler if this doesn't need to consider alignment.
1034       static_assert(alignof(T) == alignof(void *),
1035                     "Only works for pointer-aligned types.");
1036       static_assert(std::is_trivial<T>::value ||
1037                         std::is_same<ImplicitConversionSequence, T>::value,
1038                     "Add destruction logic to OverloadCandidateSet::clear().");
1039 
1040       unsigned NBytes = sizeof(T) * N;
1041       if (NBytes > NumInlineBytes - NumInlineBytesUsed)
1042         return SlabAllocator.Allocate<T>(N);
1043       char *FreeSpaceStart = InlineSpace + NumInlineBytesUsed;
1044       assert(uintptr_t(FreeSpaceStart) % alignof(void *) == 0 &&
1045              "Misaligned storage!");
1046 
1047       NumInlineBytesUsed += NBytes;
1048       return reinterpret_cast<T *>(FreeSpaceStart);
1049     }
1050 
1051     void destroyCandidates();
1052 
1053     /// Whether diagnostics should be deferred.
1054     bool shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, SourceLocation OpLoc);
1055 
1056   public:
1057     OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK,
1058                          OperatorRewriteInfo RewriteInfo = {})
Loc(Loc)1059         : Loc(Loc), Kind(CSK), RewriteInfo(RewriteInfo) {}
1060     OverloadCandidateSet(const OverloadCandidateSet &) = delete;
1061     OverloadCandidateSet &operator=(const OverloadCandidateSet &) = delete;
~OverloadCandidateSet()1062     ~OverloadCandidateSet() { destroyCandidates(); }
1063 
getLocation()1064     SourceLocation getLocation() const { return Loc; }
getKind()1065     CandidateSetKind getKind() const { return Kind; }
getRewriteInfo()1066     OperatorRewriteInfo getRewriteInfo() const { return RewriteInfo; }
1067 
1068     /// Determine when this overload candidate will be new to the
1069     /// overload set.
1070     bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO =
1071                                      OverloadCandidateParamOrder::Normal) {
1072       uintptr_t Key = reinterpret_cast<uintptr_t>(F->getCanonicalDecl());
1073       Key |= static_cast<uintptr_t>(PO);
1074       return Functions.insert(Key).second;
1075     }
1076 
1077     /// Exclude a function from being considered by overload resolution.
exclude(Decl * F)1078     void exclude(Decl *F) {
1079       isNewCandidate(F, OverloadCandidateParamOrder::Normal);
1080       isNewCandidate(F, OverloadCandidateParamOrder::Reversed);
1081     }
1082 
1083     /// Clear out all of the candidates.
1084     void clear(CandidateSetKind CSK);
1085 
1086     using iterator = SmallVectorImpl<OverloadCandidate>::iterator;
1087 
begin()1088     iterator begin() { return Candidates.begin(); }
end()1089     iterator end() { return Candidates.end(); }
1090 
size()1091     size_t size() const { return Candidates.size(); }
empty()1092     bool empty() const { return Candidates.empty(); }
1093 
1094     /// Allocate storage for conversion sequences for NumConversions
1095     /// conversions.
1096     ConversionSequenceList
allocateConversionSequences(unsigned NumConversions)1097     allocateConversionSequences(unsigned NumConversions) {
1098       ImplicitConversionSequence *Conversions =
1099           slabAllocate<ImplicitConversionSequence>(NumConversions);
1100 
1101       // Construct the new objects.
1102       for (unsigned I = 0; I != NumConversions; ++I)
1103         new (&Conversions[I]) ImplicitConversionSequence();
1104 
1105       return ConversionSequenceList(Conversions, NumConversions);
1106     }
1107 
1108     /// Add a new candidate with NumConversions conversion sequence slots
1109     /// to the overload set.
1110     OverloadCandidate &addCandidate(unsigned NumConversions = 0,
1111                                     ConversionSequenceList Conversions = None) {
1112       assert((Conversions.empty() || Conversions.size() == NumConversions) &&
1113              "preallocated conversion sequence has wrong length");
1114 
1115       Candidates.push_back(OverloadCandidate());
1116       OverloadCandidate &C = Candidates.back();
1117       C.Conversions = Conversions.empty()
1118                           ? allocateConversionSequences(NumConversions)
1119                           : Conversions;
1120       return C;
1121     }
1122 
1123     /// Find the best viable function on this overload set, if it exists.
1124     OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
1125                                          OverloadCandidateSet::iterator& Best);
1126 
1127     SmallVector<OverloadCandidate *, 32> CompleteCandidates(
1128         Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
1129         SourceLocation OpLoc = SourceLocation(),
1130         llvm::function_ref<bool(OverloadCandidate &)> Filter =
1131             [](OverloadCandidate &) { return true; });
1132 
1133     void NoteCandidates(
1134         PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD,
1135         ArrayRef<Expr *> Args, StringRef Opc = "",
1136         SourceLocation Loc = SourceLocation(),
1137         llvm::function_ref<bool(OverloadCandidate &)> Filter =
1138             [](OverloadCandidate &) { return true; });
1139 
1140     void NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
1141                         ArrayRef<OverloadCandidate *> Cands,
1142                         StringRef Opc = "",
1143                         SourceLocation OpLoc = SourceLocation());
1144 
getDestAS()1145     LangAS getDestAS() { return DestAS; }
1146 
setDestAS(LangAS AS)1147     void setDestAS(LangAS AS) {
1148       assert((Kind == CSK_InitByConstructor ||
1149               Kind == CSK_InitByUserDefinedConversion) &&
1150              "can't set the destination address space when not constructing an "
1151              "object");
1152       DestAS = AS;
1153     }
1154 
1155   };
1156 
1157   bool isBetterOverloadCandidate(Sema &S,
1158                                  const OverloadCandidate &Cand1,
1159                                  const OverloadCandidate &Cand2,
1160                                  SourceLocation Loc,
1161                                  OverloadCandidateSet::CandidateSetKind Kind);
1162 
1163   struct ConstructorInfo {
1164     DeclAccessPair FoundDecl;
1165     CXXConstructorDecl *Constructor;
1166     FunctionTemplateDecl *ConstructorTmpl;
1167 
1168     explicit operator bool() const { return Constructor; }
1169   };
1170 
1171   // FIXME: Add an AddOverloadCandidate / AddTemplateOverloadCandidate overload
1172   // that takes one of these.
getConstructorInfo(NamedDecl * ND)1173   inline ConstructorInfo getConstructorInfo(NamedDecl *ND) {
1174     if (isa<UsingDecl>(ND))
1175       return ConstructorInfo{};
1176 
1177     // For constructors, the access check is performed against the underlying
1178     // declaration, not the found declaration.
1179     auto *D = ND->getUnderlyingDecl();
1180     ConstructorInfo Info = {DeclAccessPair::make(ND, D->getAccess()), nullptr,
1181                             nullptr};
1182     Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
1183     if (Info.ConstructorTmpl)
1184       D = Info.ConstructorTmpl->getTemplatedDecl();
1185     Info.Constructor = dyn_cast<CXXConstructorDecl>(D);
1186     return Info;
1187   }
1188 
1189 } // namespace clang
1190 
1191 #endif // LLVM_CLANG_SEMA_OVERLOAD_H
1192