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

source code of clang/include/clang/Sema/Overload.h