clang: recusive lambdas in templates can segfault by exausting stack
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
Compiling the following code causes a stack overflow on `clang++ std=c++23`
```c++
struct foo_tag {};
template struct foo {
using tag = foo_tag;
T run;
};
template concept isFoo = requires(T a) {a.run();};
//function to construct very complex type with lambda
template auto complexify(T a) requires isFoo {
if constexpr (i > 0) {
return complexify(foo{ [a]{
return 1+a.run();
}});
} else return a;
}
//base case
template auto complexify(int a) {
return complexify(foo{ [a]{
return a;
}});
}
int main() {
auto a = complexify<389>(1);
}
// vim: ts=2 sw=2
```
Output that the main version of clang outputs:
[output.txt](https://github.com/user-attachments/files/25141859/output.txt)
and the files it wishes me to attach:
[clang-bug-c2e6e3.sh](https://github.com/user-attachments/files/25141857/clang-bug-c2e6e3.sh)
[clang-bug-c2e6e3.cpp](https://github.com/user-attachments/files/25141858/clang-bug-c2e6e3.cpp)
by adjusting `complexify<398>(t)` to be a slightly smaller (for example, `381` on my machine + build), I get a warning about the stack being nearly exhausted.
```
clang-bug.cpp:3:26: warning: stack nearly exhausted; compilation time may suffer, and crashes due to stack overflow
are likely [-Wstack-exhausted]
```
g++ compiles it without issue. (though it has a related bug ([Bug 120124](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120124)) where it crashes there is an error message that involves this; which is how I found this clang bug by accident)
Contributor guide
Research direction
Start by compiling the attached clang-bug-c2e6e3.cpp with clang++ in C++23 mode and compare the result with output.txt. Investigate the stack-exhaustion warning and crash around the recursive template and lambda instantiations; done means the reproducer no longer exhausts the compiler stack or receives an appropriate diagnostic.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100