Issue 235703
Summary [clang] Discarded enable_if diagnostics expand a repeated type exponentially
Labels clang
Assignees
Reporter adamtheturtle
    Tested with official LLVM 23.1.4 (`7a941dfb2877a0b8cf30323fefa85ad019e0b0f5`) on Ubuntu 24.04.5, Linux AArch64.

A valid overload call should select the ellipsis overload without constructing an unused diagnostic string.
The qualified `::accept` call intentionally disables ADL, isolating diagnostic construction.

```cpp
#include <type_traits>
template<class T, class U=T> struct Node {};
template<class T, std::enable_if_t<(sizeof(T) == 0), int> = 0> void accept(T) {}
void accept(...) {}
int main() { ::accept(Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}); }
```

Run from the [reproducer bundle](https://github.com/adamtheturtle/literalizer/blob/609a43270048ac5e733e14b320fc667f6cc5429e/ci/llvm-upstream/README.md):

```sh
timeout 10s clang++ -std=c++17 -fsyntax-only reproducers/sfinae.cpp
```

The unmodified release exceeded the ten-second limit (exit 124).
The same input completed in 0.028 seconds with the [candidate implementation](https://github.com/adamtheturtle/literalizer/blob/609a43270048ac5e733e14b320fc667f6cc5429e/ci/llvm-upstream/patches/sfinae.patch).
These are single sequential wall-clock samples, not statistical benchmarks.
Raw commands and outputs are in [measurements.json](https://github.com/adamtheturtle/literalizer/blob/609a43270048ac5e733e14b320fc667f6cc5429e/ci/llvm-upstream/measurements.json).

The false `sizeof(T) == 0` requirement is cheap to evaluate.
The expensive work is eagerly pretty-printing its substituted type for a diagnostic that is discarded when the fallback overload succeeds.

Candidate fix: Defer formatting the failed boolean condition until a rejected candidate is actually diagnosed.
Keep _expression_ evaluation and overload viability unchanged.
The candidate patch includes a compiler-driven regression test.

The isolated patch applies to LLVM main `fac4500420cdeed42f35537a26eea1e4e17badf0` and contains a regression test.
The new test and the downstream semantic controls were run with the patched 23.1.4 tools; a complete build of current LLVM main has not been performed.

The older https://github.com/llvm/llvm-project/issues/38701 is related compile-time-performance context, rather than a demonstrated duplicate of this reduced case.

Related report: https://github.com/llvm/llvm-project/issues/35506 also concerns SFINAE cost in template parameter lists; equivalence to this diagnostic-formatting case has not been established.

Prepared with AI assistance.

<details>
<summary>Candidate patch, including regression test</summary>

```diff
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index c56f8127..6fe31952 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -12724,9 +12724,17 @@ static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
     // We found a specific requirement that disabled the enable_if.
     if (PDiag && PDiag->second.getDiagID() ==
 diag::err_typename_nested_not_found_requirement) {
+      auto *Storage = PDiag->second.getStorage();
+      std::string Description;
+      if (Storage->DiagArgumentsKind[0] == DiagnosticsEngine::ak_expr) {
+ auto *Cond = reinterpret_cast<Expr *>(Storage->DiagArgumentsVal[0]);
+ Description = S.findFailedBooleanCondition(Cond).second;
+      } else {
+ Description = PDiag->second.getStringArg(0).str();
+      }
 S.Diag(Templated->getLocation(),
 diag::note_ovl_candidate_disabled_by_requirement)
-        << PDiag->second.getStringArg(0) << TemplateArgString;
+          << Description << TemplateArgString;
       return;
     }

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index ec1f8077..d6b6492e 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3718,9 +3718,8 @@ private:

 } // end anonymous namespace

-std::pair<Expr *, std::string>
-Sema::findFailedBooleanCondition(Expr *Cond) {
-  Cond = lookThroughRangesV3Condition(PP, Cond);
+static Expr *findFailedBooleanConditionExpr(Sema &S, Expr *Cond) {
+  Cond = lookThroughRangesV3Condition(S.getPreprocessor(), Cond);

   // Separate out all of the terms in a conjunction.
   SmallVector<Expr *, 4> Terms;
@@ -3739,10 +3738,10 @@ Sema::findFailedBooleanCondition(Expr *Cond) {
     // The initialization of the parameter from the argument is
     // a constant-evaluated context.
     EnterExpressionEvaluationContext ConstantEvaluated(
-      *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
+      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);

     bool Succeeded;
-    if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
+    if (Term->EvaluateAsBooleanCondition(Succeeded, S.Context) &&
 !Succeeded) {
       FailedCond = TermAsWritten;
       break;
@@ -3751,6 +3750,12 @@ Sema::findFailedBooleanCondition(Expr *Cond) {
   if (!FailedCond)
     FailedCond = Cond->IgnoreParenImpCasts();

+  return FailedCond;
+}
+
+std::pair<Expr *, std::string>
+Sema::findFailedBooleanCondition(Expr *Cond) {
+  Expr *FailedCond = findFailedBooleanConditionExpr(*this, Cond);
   std::string Description;
   {
     llvm::raw_string_ostream Out(Description);
@@ -3927,10 +3932,10 @@ QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
                   diag::err_typename_nested_not_found_enable_if &&
               TemplateArgs[0].getArgument().getKind() ==
 TemplateArgument::_expression_) {
-            Expr *FailedCond;
- std::string FailedDescription;
-            std::tie(FailedCond, FailedDescription) =
- findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
+ // Keep the _expression_ until a failed candidate is diagnosed.
+ // Formatting canonical types here expands discarded candidates.
+ Expr *FailedCond = findFailedBooleanConditionExpr(
+                *this, TemplateArgs[0].getSourceExpression());

             // Remove the old SFINAE diagnostic.
             PartialDiagnosticAt OldDiag =
@@ -3942,7 +3947,7 @@ QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
             DeductionInfo->addSFINAEDiagnostic(
 OldDiag.first,
 PDiag(diag::err_typename_nested_not_found_requirement)
- << FailedDescription << FailedCond->getSourceRange());
+ << FailedCond << FailedCond->getSourceRange());
           }
         }
 }
@@ -11521,15 +11526,15 @@ Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
       // If we have a condition, narrow it down to the specific failed
       // condition.
 if (Cond) {
-        Expr *FailedCond;
-        std::string FailedDescription;
-        std::tie(FailedCond, FailedDescription) =
- findFailedBooleanCondition(Cond);
-
- Diag(FailedCond->getExprLoc(),
- diag::err_typename_nested_not_found_requirement)
-          << FailedDescription
-          << FailedCond->getSourceRange();
+        Expr *FailedCond = findFailedBooleanConditionExpr(*this, Cond);
+
+        auto DB = Diag(FailedCond->getExprLoc(),
+ diag::err_typename_nested_not_found_requirement);
+        if (getSFINAEContext())
+          DB << FailedCond;
+        else
+ DB << findFailedBooleanCondition(FailedCond).second;
+        DB << FailedCond->getSourceRange();
         return QualType();
       }

diff --git a/clang/test/SemaTemplate/enable-if-discarded-deep-diagnostic.cpp b/clang/test/SemaTemplate/enable-if-discarded-deep-diagnostic.cpp
new file mode 100644
index 0000000000000..ad99cf6990467b236ac274d77376e963221cca57
--- /dev/null
+++ b/clang/test/SemaTemplate/enable-if-discarded-deep-diagnostic.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+namespace std {
+template<bool, class T=void> struct enable_if {};
+template<class T> struct enable_if<true,T> { using type=T; };
+template<bool B, class T=void> using enable_if_t=typename enable_if<B,T>::type;
+}
+template<class T, class U=T> struct Node {};
+template<class T, std::enable_if_t<(sizeof(T) == 0), int> = 0> void accept(T) {}
+void accept(...) {}
+int main() { ::accept(Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<Node<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}); }

```

</details>


_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to