<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/99877>99877</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Crash when evaluating folds involving lambdas and variadic templates
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            clang:frontend
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
            ilya-biryukov
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          ilya-biryukov
      </td>
    </tr>
</table>

<pre>
    On this code:
```cpp
struct tuple {
    int x[3];
};

template <class F>
void apply(F f, tuple v) {
    return f(v.x[0], v.x[1], v.x[2]);
}

void Cartesian(auto x, auto y) {
 apply([&](auto... xs) {
        (apply([xs](auto... ys) {
 (ys + ...);
        }, y), ...);
    }, x);
}

int main() {
    auto x = tuple({1, 2, 3});
    auto y = tuple({4, 5, 6});
 Cartesian(x, y);
}
```

Clang will crash with a following assertion error:
```
clang++: /root/llvm-project/clang/lib/Sema/TreeTransform.h:15248: clang::ExprResult clang::TreeTransform<Derived>::TransformCXXFoldExpr(clang::CXXFoldExpr*) [with Derived = {anonymous}::TemplateInstantiator; clang::ExprResult = clang::ActionResult<clang::Expr*>]: Assertion `!Unexpanded.empty() && "Pack expansion without parameter packs?"' failed.
```

The problem arises because when substituting into inner lambdas, Clang will incorrectly loose the `ContainsUnexpandedPack` dependency on a lambda expression. In turn, this confuses the `CXXFoldExpr` that relies in this flag to distinguish left and right folds, which will pass the `nullptr` expr to `CollectUnexpandedParameterPacks` and cause it to not find any packs when transforming the fold expression, leading to an asssertion.

I have already been working on a fix for a few days and more sophisticated tests, so assigning to myself right away.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJx8Vd2u2jgQfhpzM2oUHCBwwQVwitSrrXa7Um8HeyDeY-zIdoC8_Wqc0Iae3R6hnDjz-33zY4zRXBzRViz3Qkpje_x0MqHv3v1NSCmWbzPsUuPD9kU0O3ndb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