1 //===--- Overload.h - C++ Overloading ---------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the data structures and types used in C++
11 // overload resolution.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_OVERLOAD_H
16 #define LLVM_CLANG_SEMA_OVERLOAD_H
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/TemplateBase.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/UnresolvedSet.h"
24 #include "clang/Sema/SemaFixItUtils.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
30 class CXXConstructorDecl;
31 class CXXConversionDecl;
35 /// OverloadingResult - Capture the result of performing overload
37 enum OverloadingResult {
38 OR_Success, ///< Overload resolution succeeded.
39 OR_No_Viable_Function, ///< No viable function found.
40 OR_Ambiguous, ///< Ambiguous candidates found.
41 OR_Deleted ///< Succeeded, but refers to a deleted function.
44 enum OverloadCandidateDisplayKind {
45 /// Requests that all candidates be shown. Viable candidates will
49 /// Requests that only viable candidates be shown.
53 /// ImplicitConversionKind - The kind of implicit conversion used to
54 /// convert an argument to a parameter's type. The enumerator values
55 /// match with Table 9 of (C++ 13.3.3.1.1) and are listed such that
56 /// better conversion kinds have smaller values.
57 enum ImplicitConversionKind {
58 ICK_Identity = 0, ///< Identity conversion (no conversion)
59 ICK_Lvalue_To_Rvalue, ///< Lvalue-to-rvalue conversion (C++ 4.1)
60 ICK_Array_To_Pointer, ///< Array-to-pointer conversion (C++ 4.2)
61 ICK_Function_To_Pointer, ///< Function-to-pointer (C++ 4.3)
62 ICK_NoReturn_Adjustment, ///< Removal of noreturn from a type (Clang)
63 ICK_Qualification, ///< Qualification conversions (C++ 4.4)
64 ICK_Integral_Promotion, ///< Integral promotions (C++ 4.5)
65 ICK_Floating_Promotion, ///< Floating point promotions (C++ 4.6)
66 ICK_Complex_Promotion, ///< Complex promotions (Clang extension)
67 ICK_Integral_Conversion, ///< Integral conversions (C++ 4.7)
68 ICK_Floating_Conversion, ///< Floating point conversions (C++ 4.8)
69 ICK_Complex_Conversion, ///< Complex conversions (C99 6.3.1.6)
70 ICK_Floating_Integral, ///< Floating-integral conversions (C++ 4.9)
71 ICK_Pointer_Conversion, ///< Pointer conversions (C++ 4.10)
72 ICK_Pointer_Member, ///< Pointer-to-member conversions (C++ 4.11)
73 ICK_Boolean_Conversion, ///< Boolean conversions (C++ 4.12)
74 ICK_Compatible_Conversion, ///< Conversions between compatible types in C99
75 ICK_Derived_To_Base, ///< Derived-to-base (C++ [over.best.ics])
76 ICK_Vector_Conversion, ///< Vector conversions
77 ICK_Vector_Splat, ///< A vector splat from an arithmetic type
78 ICK_Complex_Real, ///< Complex-real conversions (C99 6.3.1.7)
79 ICK_Block_Pointer_Conversion, ///< Block Pointer conversions
80 ICK_TransparentUnionConversion, /// Transparent Union Conversions
81 ICK_Writeback_Conversion, ///< Objective-C ARC writeback conversion
82 ICK_Num_Conversion_Kinds ///< The number of conversion kinds
85 /// ImplicitConversionCategory - The category of an implicit
86 /// conversion kind. The enumerator values match with Table 9 of
87 /// (C++ 13.3.3.1.1) and are listed such that better conversion
88 /// categories have smaller values.
89 enum ImplicitConversionCategory {
90 ICC_Identity = 0, ///< Identity
91 ICC_Lvalue_Transformation, ///< Lvalue transformation
92 ICC_Qualification_Adjustment, ///< Qualification adjustment
93 ICC_Promotion, ///< Promotion
94 ICC_Conversion ///< Conversion
97 ImplicitConversionCategory
98 GetConversionCategory(ImplicitConversionKind Kind);
100 /// ImplicitConversionRank - The rank of an implicit conversion
101 /// kind. The enumerator values match with Table 9 of (C++
102 /// 13.3.3.1.1) and are listed such that better conversion ranks
103 /// have smaller values.
104 enum ImplicitConversionRank {
105 ICR_Exact_Match = 0, ///< Exact Match
106 ICR_Promotion, ///< Promotion
107 ICR_Conversion, ///< Conversion
108 ICR_Complex_Real_Conversion, ///< Complex <-> Real conversion
109 ICR_Writeback_Conversion ///< ObjC ARC writeback conversion
112 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
114 /// StandardConversionSequence - represents a standard conversion
115 /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
116 /// contains between zero and three conversions. If a particular
117 /// conversion is not needed, it will be set to the identity conversion
118 /// (ICK_Identity). Note that the three conversions are
119 /// specified as separate members (rather than in an array) so that
120 /// we can keep the size of a standard conversion sequence to a
122 class StandardConversionSequence {
124 /// First -- The first conversion can be an lvalue-to-rvalue
125 /// conversion, array-to-pointer conversion, or
126 /// function-to-pointer conversion.
127 ImplicitConversionKind First : 8;
129 /// Second - The second conversion can be an integral promotion,
130 /// floating point promotion, integral conversion, floating point
131 /// conversion, floating-integral conversion, pointer conversion,
132 /// pointer-to-member conversion, or boolean conversion.
133 ImplicitConversionKind Second : 8;
135 /// Third - The third conversion can be a qualification conversion.
136 ImplicitConversionKind Third : 8;
138 /// \brief Whether this is the deprecated conversion of a
139 /// string literal to a pointer to non-const character data
141 unsigned DeprecatedStringLiteralToCharPtr : 1;
143 /// \brief Whether the qualification conversion involves a change in the
144 /// Objective-C lifetime (for automatic reference counting).
145 unsigned QualificationIncludesObjCLifetime : 1;
147 /// IncompatibleObjC - Whether this is an Objective-C conversion
148 /// that we should warn about (if we actually use it).
149 unsigned IncompatibleObjC : 1;
151 /// ReferenceBinding - True when this is a reference binding
152 /// (C++ [over.ics.ref]).
153 unsigned ReferenceBinding : 1;
155 /// DirectBinding - True when this is a reference binding that is a
156 /// direct binding (C++ [dcl.init.ref]).
157 unsigned DirectBinding : 1;
159 /// \brief Whether this is an lvalue reference binding (otherwise, it's
160 /// an rvalue reference binding).
161 unsigned IsLvalueReference : 1;
163 /// \brief Whether we're binding to a function lvalue.
164 unsigned BindsToFunctionLvalue : 1;
166 /// \brief Whether we're binding to an rvalue.
167 unsigned BindsToRvalue : 1;
169 /// \brief Whether this binds an implicit object argument to a
170 /// non-static member function without a ref-qualifier.
171 unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
173 /// \brief Whether this binds a reference to an object with a different
174 /// Objective-C lifetime qualifier.
175 unsigned ObjCLifetimeConversionBinding : 1;
177 /// FromType - The type that this conversion is converting
178 /// from. This is an opaque pointer that can be translated into a
182 /// ToType - The types that this conversion is converting to in
183 /// each step. This is an opaque pointer that can be translated
187 /// CopyConstructor - The copy constructor that is used to perform
188 /// this conversion, when the conversion is actually just the
189 /// initialization of an object via copy constructor. Such
190 /// conversions are either identity conversions or derived-to-base
192 CXXConstructorDecl *CopyConstructor;
194 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
195 void setToType(unsigned Idx, QualType T) {
196 assert(Idx < 3 && "To type index is out of range");
197 ToTypePtrs[Idx] = T.getAsOpaquePtr();
199 void setAllToTypes(QualType T) {
200 ToTypePtrs[0] = T.getAsOpaquePtr();
201 ToTypePtrs[1] = ToTypePtrs[0];
202 ToTypePtrs[2] = ToTypePtrs[0];
205 QualType getFromType() const {
206 return QualType::getFromOpaquePtr(FromTypePtr);
208 QualType getToType(unsigned Idx) const {
209 assert(Idx < 3 && "To type index is out of range");
210 return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
213 void setAsIdentityConversion();
215 bool isIdentityConversion() const {
216 return Second == ICK_Identity && Third == ICK_Identity;
219 ImplicitConversionRank getRank() const;
220 bool isPointerConversionToBool() const;
221 bool isPointerConversionToVoidPointer(ASTContext& Context) const;
222 void DebugPrint() const;
225 /// UserDefinedConversionSequence - Represents a user-defined
226 /// conversion sequence (C++ 13.3.3.1.2).
227 struct UserDefinedConversionSequence {
228 /// Before - Represents the standard conversion that occurs before
229 /// the actual user-defined conversion. (C++ 13.3.3.1.2p1):
231 /// If the user-defined conversion is specified by a constructor
232 /// (12.3.1), the initial standard conversion sequence converts
233 /// the source type to the type required by the argument of the
234 /// constructor. If the user-defined conversion is specified by
235 /// a conversion function (12.3.2), the initial standard
236 /// conversion sequence converts the source type to the implicit
237 /// object parameter of the conversion function.
238 StandardConversionSequence Before;
240 /// EllipsisConversion - When this is true, it means user-defined
241 /// conversion sequence starts with a ... (elipsis) conversion, instead of
242 /// a standard conversion. In this case, 'Before' field must be ignored.
243 // FIXME. I much rather put this as the first field. But there seems to be
244 // a gcc code gen. bug which causes a crash in a test. Putting it here seems
245 // to work around the crash.
246 bool EllipsisConversion : 1;
248 /// HadMultipleCandidates - When this is true, it means that the
249 /// conversion function was resolved from an overloaded set having
250 /// size greater than 1.
251 bool HadMultipleCandidates : 1;
253 /// After - Represents the standard conversion that occurs after
254 /// the actual user-defined conversion.
255 StandardConversionSequence After;
257 /// ConversionFunction - The function that will perform the
258 /// user-defined conversion.
259 FunctionDecl* ConversionFunction;
261 /// \brief The declaration that we found via name lookup, which might be
262 /// the same as \c ConversionFunction or it might be a using declaration
263 /// that refers to \c ConversionFunction.
264 DeclAccessPair FoundConversionFunction;
266 void DebugPrint() const;
269 /// Represents an ambiguous user-defined conversion sequence.
270 struct AmbiguousConversionSequence {
271 typedef SmallVector<FunctionDecl*, 4> ConversionSet;
275 char Buffer[sizeof(ConversionSet)];
277 QualType getFromType() const {
278 return QualType::getFromOpaquePtr(FromTypePtr);
280 QualType getToType() const {
281 return QualType::getFromOpaquePtr(ToTypePtr);
283 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
284 void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
286 ConversionSet &conversions() {
287 return *reinterpret_cast<ConversionSet*>(Buffer);
290 const ConversionSet &conversions() const {
291 return *reinterpret_cast<const ConversionSet*>(Buffer);
294 void addConversion(FunctionDecl *D) {
295 conversions().push_back(D);
298 typedef ConversionSet::iterator iterator;
299 iterator begin() { return conversions().begin(); }
300 iterator end() { return conversions().end(); }
302 typedef ConversionSet::const_iterator const_iterator;
303 const_iterator begin() const { return conversions().begin(); }
304 const_iterator end() const { return conversions().end(); }
308 void copyFrom(const AmbiguousConversionSequence &);
311 /// BadConversionSequence - Records information about an invalid
312 /// conversion sequence.
313 struct BadConversionSequence {
319 lvalue_ref_to_rvalue,
323 // This can be null, e.g. for implicit object arguments.
329 // The type we're converting from (an opaque QualType).
332 // The type we're converting to (an opaque QualType).
336 void init(FailureKind K, Expr *From, QualType To) {
337 init(K, From->getType(), To);
340 void init(FailureKind K, QualType From, QualType To) {
347 QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
348 QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
350 void setFromExpr(Expr *E) {
352 setFromType(E->getType());
354 void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
355 void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
358 /// ImplicitConversionSequence - Represents an implicit conversion
359 /// sequence, which may be a standard conversion sequence
360 /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
361 /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
362 class ImplicitConversionSequence {
364 /// Kind - The kind of implicit conversion sequence. BadConversion
365 /// specifies that there is no conversion from the source type to
366 /// the target type. AmbiguousConversion represents the unique
367 /// ambiguous conversion (C++0x [over.best.ics]p10).
369 StandardConversion = 0,
370 UserDefinedConversion,
378 Uninitialized = BadConversion + 1
381 /// ConversionKind - The kind of implicit conversion sequence.
382 unsigned ConversionKind;
384 void setKind(Kind K) {
390 if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
395 /// When ConversionKind == StandardConversion, provides the
396 /// details of the standard conversion sequence.
397 StandardConversionSequence Standard;
399 /// When ConversionKind == UserDefinedConversion, provides the
400 /// details of the user-defined conversion sequence.
401 UserDefinedConversionSequence UserDefined;
403 /// When ConversionKind == AmbiguousConversion, provides the
404 /// details of the ambiguous conversion.
405 AmbiguousConversionSequence Ambiguous;
407 /// When ConversionKind == BadConversion, provides the details
408 /// of the bad conversion.
409 BadConversionSequence Bad;
412 ImplicitConversionSequence() : ConversionKind(Uninitialized) {}
413 ~ImplicitConversionSequence() {
416 ImplicitConversionSequence(const ImplicitConversionSequence &Other)
417 : ConversionKind(Other.ConversionKind)
419 switch (ConversionKind) {
420 case Uninitialized: break;
421 case StandardConversion: Standard = Other.Standard; break;
422 case UserDefinedConversion: UserDefined = Other.UserDefined; break;
423 case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
424 case EllipsisConversion: break;
425 case BadConversion: Bad = Other.Bad; break;
429 ImplicitConversionSequence &
430 operator=(const ImplicitConversionSequence &Other) {
432 new (this) ImplicitConversionSequence(Other);
436 Kind getKind() const {
437 assert(isInitialized() && "querying uninitialized conversion");
438 return Kind(ConversionKind);
441 /// \brief Return a ranking of the implicit conversion sequence
442 /// kind, where smaller ranks represent better conversion
445 /// In particular, this routine gives user-defined conversion
446 /// sequences and ambiguous conversion sequences the same rank,
447 /// per C++ [over.best.ics]p10.
448 unsigned getKindRank() const {
450 case StandardConversion:
453 case UserDefinedConversion:
454 case AmbiguousConversion:
457 case EllipsisConversion:
467 bool isBad() const { return getKind() == BadConversion; }
468 bool isStandard() const { return getKind() == StandardConversion; }
469 bool isEllipsis() const { return getKind() == EllipsisConversion; }
470 bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
471 bool isUserDefined() const { return getKind() == UserDefinedConversion; }
472 bool isFailure() const { return isBad() || isAmbiguous(); }
474 /// Determines whether this conversion sequence has been
475 /// initialized. Most operations should never need to query
476 /// uninitialized conversions and should assert as above.
477 bool isInitialized() const { return ConversionKind != Uninitialized; }
479 /// Sets this sequence as a bad conversion for an explicit argument.
480 void setBad(BadConversionSequence::FailureKind Failure,
481 Expr *FromExpr, QualType ToType) {
482 setKind(BadConversion);
483 Bad.init(Failure, FromExpr, ToType);
486 /// Sets this sequence as a bad conversion for an implicit argument.
487 void setBad(BadConversionSequence::FailureKind Failure,
488 QualType FromType, QualType ToType) {
489 setKind(BadConversion);
490 Bad.init(Failure, FromType, ToType);
493 void setStandard() { setKind(StandardConversion); }
494 void setEllipsis() { setKind(EllipsisConversion); }
495 void setUserDefined() { setKind(UserDefinedConversion); }
496 void setAmbiguous() {
497 if (ConversionKind == AmbiguousConversion) return;
498 ConversionKind = AmbiguousConversion;
499 Ambiguous.construct();
502 // The result of a comparison between implicit conversion
503 // sequences. Use Sema::CompareImplicitConversionSequences to
504 // actually perform the comparison.
507 Indistinguishable = 0,
511 void DiagnoseAmbiguousConversion(Sema &S,
512 SourceLocation CaretLoc,
513 const PartialDiagnostic &PDiag) const;
515 void DebugPrint() const;
518 enum OverloadFailureKind {
519 ovl_fail_too_many_arguments,
520 ovl_fail_too_few_arguments,
521 ovl_fail_bad_conversion,
522 ovl_fail_bad_deduction,
524 /// This conversion candidate was not considered because it
525 /// duplicates the work of a trivial or derived-to-base
527 ovl_fail_trivial_conversion,
529 /// This conversion candidate is not viable because its result
530 /// type is not implicitly convertible to the desired type.
531 ovl_fail_bad_final_conversion,
533 /// This conversion function template specialization candidate is not
534 /// viable because the final conversion was not an exact match.
535 ovl_fail_final_conversion_not_exact,
537 /// (CUDA) This candidate was not viable because the callee
538 /// was not accessible from the caller's target (i.e. host->device,
539 /// global->host, device->host).
543 /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
544 struct OverloadCandidate {
545 /// Function - The actual function that this candidate
546 /// represents. When NULL, this is a built-in candidate
547 /// (C++ [over.oper]) or a surrogate for a conversion to a
548 /// function pointer or reference (C++ [over.call.object]).
549 FunctionDecl *Function;
551 /// FoundDecl - The original declaration that was looked up /
552 /// invented / otherwise found, together with its access.
553 /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
554 DeclAccessPair FoundDecl;
556 // BuiltinTypes - Provides the return and parameter types of a
557 // built-in overload candidate. Only valid when Function is NULL.
560 QualType ParamTypes[3];
563 /// Surrogate - The conversion function for which this candidate
564 /// is a surrogate, but only if IsSurrogate is true.
565 CXXConversionDecl *Surrogate;
567 /// Conversions - The conversion sequences used to convert the
568 /// function arguments to the function parameters.
569 SmallVector<ImplicitConversionSequence, 4> Conversions;
571 /// The FixIt hints which can be used to fix the Bad candidate.
572 ConversionFixItGenerator Fix;
574 /// Viable - True to indicate that this overload candidate is viable.
577 /// IsSurrogate - True to indicate that this candidate is a
578 /// surrogate for a conversion to a function pointer or reference
579 /// (C++ [over.call.object]).
582 /// IgnoreObjectArgument - True to indicate that the first
583 /// argument's conversion, which for this function represents the
584 /// implicit object argument, should be ignored. This will be true
585 /// when the candidate is a static member function (where the
586 /// implicit object argument is just a placeholder) or a
587 /// non-static member function when the call doesn't have an
589 bool IgnoreObjectArgument;
591 /// FailureKind - The reason why this candidate is not viable.
592 /// Actually an OverloadFailureKind.
593 unsigned char FailureKind;
595 /// \brief The number of call arguments that were explicitly provided,
596 /// to be used while performing partial ordering of function templates.
597 unsigned ExplicitCallArguments;
599 /// A structure used to record information about a failed
600 /// template argument deduction.
601 struct DeductionFailureInfo {
602 // A Sema::TemplateDeductionResult.
605 /// \brief Opaque pointer containing additional data about
606 /// this deduction failure.
609 /// \brief Retrieve the template parameter this deduction failure
610 /// refers to, if any.
611 TemplateParameter getTemplateParameter();
613 /// \brief Retrieve the template argument list associated with this
614 /// deduction failure, if any.
615 TemplateArgumentList *getTemplateArgumentList();
617 /// \brief Return the first template argument this deduction failure
618 /// refers to, if any.
619 const TemplateArgument *getFirstArg();
621 /// \brief Return the second template argument this deduction failure
622 /// refers to, if any.
623 const TemplateArgument *getSecondArg();
625 /// \brief Free any memory associated with this deduction failure.
630 DeductionFailureInfo DeductionFailure;
632 /// FinalConversion - For a conversion function (where Function is
633 /// a CXXConversionDecl), the standard conversion that occurs
634 /// after the call to the overload candidate to convert the result
635 /// of calling the conversion function to the required type.
636 StandardConversionSequence FinalConversion;
639 /// hasAmbiguousConversion - Returns whether this overload
640 /// candidate requires an ambiguous conversion or not.
641 bool hasAmbiguousConversion() const {
642 for (SmallVectorImpl<ImplicitConversionSequence>::const_iterator
643 I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
644 if (!I->isInitialized()) return false;
645 if (I->isAmbiguous()) return true;
650 bool TryToFixBadConversion(unsigned Idx, Sema &S) {
651 bool CanFix = Fix.tryToFixConversion(
652 Conversions[Idx].Bad.FromExpr,
653 Conversions[Idx].Bad.getFromType(),
654 Conversions[Idx].Bad.getToType(), S);
656 // If at least one conversion fails, the candidate cannot be fixed.
664 /// OverloadCandidateSet - A set of overload candidates, used in C++
665 /// overload resolution (C++ 13.3).
666 class OverloadCandidateSet : public SmallVector<OverloadCandidate, 16> {
667 typedef SmallVector<OverloadCandidate, 16> inherited;
668 llvm::SmallPtrSet<Decl *, 16> Functions;
672 OverloadCandidateSet(const OverloadCandidateSet &);
673 OverloadCandidateSet &operator=(const OverloadCandidateSet &);
676 OverloadCandidateSet(SourceLocation Loc) : Loc(Loc) {}
678 SourceLocation getLocation() const { return Loc; }
680 /// \brief Determine when this overload candidate will be new to the
682 bool isNewCandidate(Decl *F) {
683 return Functions.insert(F->getCanonicalDecl());
686 /// \brief Clear out all of the candidates.
689 /// Find the best viable function on this overload set, if it exists.
690 OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
691 OverloadCandidateSet::iterator& Best,
692 bool UserDefinedConversion = false);
694 void NoteCandidates(Sema &S,
695 OverloadCandidateDisplayKind OCD,
696 Expr **Args, unsigned NumArgs,
698 SourceLocation Loc = SourceLocation());
701 bool isBetterOverloadCandidate(Sema &S,
702 const OverloadCandidate& Cand1,
703 const OverloadCandidate& Cand2,
705 bool UserDefinedConversion = false);
706 } // end namespace clang
708 #endif // LLVM_CLANG_SEMA_OVERLOAD_H