← Back to Pull requests

Reapply "[Clang][Sema] Fix rejecting valid reference initialization with conversion function templates" (#237716) #237738

Open
IvyXu420 opened this pull request with 77 lines diff across 7 files
View on GitHub
IvyXu420 IvyXu420 commented on Nov 01, 2026 14:22 UTC
Author

This reverts commit https://github.com/llvm/llvm-project/commit/9022da974a0df0d4f09021f2ee141278e0b34b38.

This reland rejects invalid template specializations in Sema::AddConversionCandidate(...), which was the missed part in the previous fix.

Closes #226984.

Diff: 77 lines (+60 / -17) across 7 files Reviewer: zyn0217 Review duration: 48159m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.45) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.45 · 77 lines diff across 7 files
0.45
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.90 · 5 substantive comment(s)
0.90
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.261
Real PR Conversation Timeline
8 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Nov 01, 2026 14:23 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Ivy Xu (IvyXu420)

<details>
<summary>Changes</summary>

This reverts commit https://github.com/llvm/llvm-project/commit/9022da974a0df0d4f09021f2ee141278e0b34b38.

This reland rejects invalid template specializations in AddTemplateConversionCandidateImmediately(...), which was the missed part in the previous fix.

Closes #<!-- -->226984.

---
Full diff: https://github.com/llvm/llvm-project/pull/237738.diff

7 Files Affected:

  • (modified) clang/docs/ReleaseNotes.md (+3)

  • (modified) clang/include/clang/Sema/Overload.h (+2-1)

  • (modified) clang/include/clang/Sema/Sema.h (+2-1)

  • (modified) clang/lib/Sema/SemaInit.cpp (+6-4)

  • (modified) clang/lib/Sema/SemaOverload.cpp (+13-8)

  • (modified) clang/test/SemaCXX/conversion-function.cpp (+13)

  • (modified) clang/test/SemaCXX/cxx1y-generic-lambdas.cpp (+3-1)
  • ``````

    diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
    index d2df8fe262fbff..a2ad6d06815c7c 100644
    --- a/clang/docs/ReleaseNotes.md
    +++ b/clang/docs/ReleaseNotes.md
    @@ -897,6 +897,9 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
       `sized_by_or_null` describe the size in bytes rather than a count of elements,
       they are now correctly accepted on such pointers.
     
    +- Fixed rejecting valid reference initialization with conversion function templates whose returned type is depending on 
    +  template parameters. (#GH226984)
    +
     - Fixed a crash when an `address_space` attribute with a dependent argument was
       written after the declarator-id, where it appertains to the declared entity
       rather than to a declarator chunk. (#GH196982, #GH111463)
    diff --git a/clang/include/clang/Sema/Overload.h b/clang/include/clang/Sema/Overload.h
    index f280c6ffa5a810..bb317aa094172c 100644
    --- a/clang/include/clang/Sema/Overload.h
    +++ b/clang/include/clang/Sema/Overload.h
    @@ -1154,6 +1154,7 @@ class Sema;
         CXXRecordDecl *ActingContext;
         Expr *From;
         QualType ToType;
    +    bool AllowRValues;
       };
     
       static_assert(std::is_trivially_destructible_v<
    @@ -1459,7 +1460,7 @@ class Sema;
             FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
             CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
             bool AllowObjCConversionOnExplicit, bool AllowExplicit,
    -        bool AllowResultConversion);
    +        bool AllowResultConversion, bool AllowRValues);
     
         void InjectNonDeducedTemplateCandidates(Sema &S);
     
    diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
    index ba215e7e18d7ba..698bfe1da75e09 100644
    --- a/clang/include/clang/Sema/Sema.h
    +++ b/clang/include/clang/Sema/Sema.h
    @@ -10743,7 +10743,8 @@ class Sema final : public SemaBase {
           FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
           CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
           OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
    -      bool AllowExplicit, bool AllowResultConversion = true);
    +      bool AllowExplicit, bool AllowResultConversion = true,
    +      bool AllowRValues = true);
     
       /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
       /// converts the given @c Object to a function pointer via the
    diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
    index 2e3c6309fec20e..4b241714a1cea0 100644
    --- a/clang/lib/Sema/SemaInit.cpp
    +++ b/clang/lib/Sema/SemaInit.cpp
    @@ -5384,17 +5384,19 @@ static OverloadingResult TryRefInitWithConversionFunction(
     
           // If the conversion function doesn't return a reference type,
           // it can't be considered for this conversion unless we're allowed to
    -      // consider rvalues.
    +      // consider rvalues. If it's a template, we should accept it first
    +      // and specialize it before deciding whether to reject it.
           // FIXME: Do we need to make sure that we only consider conversion
           // candidates with reference-compatible results? That might be needed to
           // break recursion.
    -      if ((AllowRValues ||
    -           Conv->getConversionType()->isLValueReferenceType())) {
    +      if (ConvTemplate || AllowRValues ||
    +          Conv->getConversionType()->isLValueReferenceType()) {
             if (ConvTemplate)
               S.AddTemplateConversionCandidate(
                   ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
                   CandidateSet,
    -              /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
    +              /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs,
    +              /*AllowResultConversion=*/true, AllowRValues);
             else
               S.AddConversionCandidate(
                   Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
    diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
    index 8219d5568bdfdd..87f20465a56b75 100644
    --- a/clang/lib/Sema/SemaOverload.cpp
    +++ b/clang/lib/Sema/SemaOverload.cpp
    @@ -8818,7 +8818,7 @@ static void AddTemplateConversionCandidateImmediately(
         FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
         CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
         bool AllowObjCConversionOnExplicit, bool AllowExplicit,
    -    bool AllowResultConversion) {
    +    bool AllowResultConversion, bool AllowRValues) {
     
       // If the function template has a non-dependent explicit specification,
       // exclude it now if appropriate; we are not permitted to perform deduction
    @@ -8852,9 +8852,13 @@ static void AddTemplateConversionCandidateImmediately(
         return;
       }
     
    +  assert(Specialization && "Missing function template specialization?");
    +  // Reject invalid template specialization.
    +  if (!AllowRValues &&
    +      !Specialization->getConversionType()->isLValueReferenceType())
    +    return;
       // Add the conversion function template specialization produced by
       // template argument deduction as a candidate.
    -  assert(Specialization && "Missing function template specialization?");
       S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
                                ToType, CandidateSet, AllowObjCConversionOnExplicit,
                                AllowExplicit, AllowResultConversion,
    @@ -8865,7 +8869,7 @@ void Sema::AddTemplateConversionCandidate(
         FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
         CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
         OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
    -    bool AllowExplicit, bool AllowResultConversion) {
    +    bool AllowExplicit, bool AllowResultConversion, bool AllowRValues) {
       assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
              "Only conversion function templates permitted here");
     
    @@ -8879,7 +8883,7 @@ void Sema::AddTemplateConversionCandidate(
         AddTemplateConversionCandidateImmediately(
             *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
             ToType, AllowObjCConversionOnExplicit, AllowExplicit,
    -        AllowResultConversion);
    +        AllowResultConversion, AllowRValues);
     
         CandidateSet.DisableResolutionByPerfectCandidate();
         return;
    @@ -8887,7 +8891,7 @@ void Sema::AddTemplateConversionCandidate(
     
       CandidateSet.AddDeferredConversionTemplateCandidate(
           FunctionTemplate, FoundDecl, ActingDC, From, ToType,
    -      AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
    +      AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion, AllowRValues);
     }
     
     void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
    @@ -11593,7 +11597,7 @@ void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
         FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
         CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
         bool AllowObjCConversionOnExplicit, bool AllowExplicit,
    -    bool AllowResultConversion) {
    +    bool AllowResultConversion, bool AllowRValues) {
     
       auto *C =
           allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
    @@ -11609,7 +11613,8 @@ void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
           FoundDecl,
           ActingContext,
           From,
    -      ToType};
    +      ToType,
    +      AllowRValues};
     }
     
     static void
    @@ -11638,7 +11643,7 @@ AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
       return AddTemplateConversionCandidateImmediately(
           S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
           C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
    -      C.AllowResultConversion);
    +      C.AllowResultConversion, C.AllowRValues);
     }
     
     void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
    diff --git a/clang/test/SemaCXX/conversion-function.cpp b/clang/test/SemaCXX/conversion-function.cpp
    index 1a09a527b750cc..629c818b89c004 100644
    --- a/clang/test/SemaCXX/conversion-function.cpp
    +++ b/clang/test/SemaCXX/conversion-function.cpp
    @@ -557,3 +557,16 @@ namespace GH189146 {
       int s = S{}(0); // expected-error {{attempt to use a deleted function}}
     }
     #endif
    +
    +#if __cplusplus >= 201402L
    +namespace GH226984 {
    +  struct A {
    +	int& ref;
    +
    +	template<int dependent = 0>
    +	operator decltype(dependent, ref)();
    +};
    +  int x = 0;
    +  int& y = A(x);
    +}
    +#endif
    diff --git a/clang/test/SemaCXX/cxx1y-generic-lambdas.cpp b/clang/test/SemaCXX/cxx1y-generic-lambdas.cpp
    index 3066bb0d0f0cc3..bb621666319046 100644
    --- a/clang/test/SemaCXX/cxx1y-generic-lambdas.cpp
    +++ b/clang/test/SemaCXX/cxx1y-generic-lambdas.cpp
    @@ -214,7 +214,9 @@ namespace conversion_operator {
       void test() {
         auto L = [](auto a) -> int { return a; }; // expected-error {{cannot initialize}}
         int (*fp)(int) = L;
    -    int (&fp2)(int) = [](auto a) { return a; };  // expected-error{{non-const lvalue}}
    +    int (&fp2)(int) = [](auto a) { return a; };
    +    // expected-error@-1   {{no viable conversion}}
    +    // expected-note-re@-2 {{candidate template ignored: could not match 'auto (*)(auto){{.*}}' against 'int (int)'}}
         int (&&fp3)(int) = [](auto a) { return a; };
         // expected-error@-1   {{no viable conversion}}
         // expected-note-re@-2 {{candidate template ignored: could not match 'auto (*)(auto){{.*}}' against 'int (int)'}}
    
    
    ``````

    </details>

    github-actions[bot] github-actions[bot] commented on Nov 01, 2026 14:24 UTC
    Bot

    <!--LLVM CODE FORMAT COMMENT: {clang-format}-->

    :white_check_mark: With the latest revision this PR passed the C/C++ code formatter.

    zwuis zwuis commented on Nov 01, 2026 15:42 UTC
    Contributor

    This reland rejects invalid template specializations in AddTemplateConversionCandidateImmediately(...), which was the missed part in the previous fix.

    Please add a test to verify that it does work.

    zyn0217 zyn0217 commented on code on Nov 02, 2026 06:19 UTC
    Code Review
    clang/lib/Sema/SemaOverload.cpp:1
    @@ -8852,9 +8852,13 @@ static void AddTemplateConversionCandidateImmediately(
         return;
       }
     
    +  assert(Specialization && "Missing function template specialization?");
    +  // Reject invalid template specialization.
    +  if (!AllowRValues &&
    +      !Specialization->getConversionType()->isLValueReferenceType())
    +    return;

    This looks very weird to me, we simply ignore a specialization without a failure reason and I'm concerned if this would affect diagnostics.

    Probably we still need these candidates and rule out them when we perform overload resolution?

    IvyXu420 IvyXu420 commented on code on Nov 02, 2026 14:30 UTC
    Code Review
    clang/lib/Sema/SemaOverload.cpp:1
    @@ -8852,9 +8852,13 @@ static void AddTemplateConversionCandidateImmediately(
         return;
       }
     
    +  assert(Specialization && "Missing function template specialization?");
    +  // Reject invalid template specialization.
    +  if (!AllowRValues &&
    +      !Specialization->getConversionType()->isLValueReferenceType())
    +    return;

    This is a filter equivalent to the one in TryRefInitWithConversionFunction(...):
    https://github.com/llvm/llvm-project/blob/836f3e4a8c6551feb35cb7a48e005b653aa774ca/clang/lib/Sema/SemaInit.cpp#L5391-L5392

    We already ignore such invalid non-template conversion functions. The only difference here is that we also ignore such invalid specializations of conversion function templates, so I don’t think this would affect diagnostics?

    However, there are also some similar cases in Sema::AddConversionCandidate(...) where we simply ignore a conversion function with a bare return;, so I think it'd be better to put these checks in that method instead.

    zyn0217 zyn0217 approved these changes on Nov 02, 2026 16:39 UTC
    Approved Reviewer

    LGTM, and @cor3ntin for the second pair of eyes

    IvyXu420 IvyXu420 commented on Nov 09, 2026 02:05 UTC
    Author

    @cor3ntin ping :)

    Reviewers
    Assignees
    IvyXu420 IvyXu420
    Labels
    risk: low confidence: 88.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 44.9% (MEDIUM) · Higher = larger blast radius
    44.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.8% · Lower = rushed or shallow review
    88.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5% · Safe to merge
    5%