| Issue |
60652
|
| Summary |
[clang++] Functions with trivial infinite loop are wrongly optimized
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
pbo-linaro
|
Given this C++ program:
```
#include <cstdio>
int main() {for(;;) {}}
```
compiled using: `clang++-15 -01 file.cpp && a.out`
One might expect to get a program never terminating.
That's the case in O0, but *not* in O1, where it returns a non-zero error code.
---
Now, consider this other program:
```
#include <cstdio>
int main() {for(;;) {} printf("Unreachable");}
void never_called() {printf("Hello world\n");}
```
In O1, it still returns a non-zero error code, but calls `never_called`!
This kind of behavior is found only in C++ (not when compiling in C).
---
**Note: The following analysis applies to any other function, not only main.**
By looking at LLVM IR (`clang++-15 -S -emit-llvm file.cpp -o -`), in O1:
```
; Function Attrs: mustprogress nofree norecurse noreturn nosync nounwind readnone willreturn uwtable
define dso_local noundef i32 @main() local_unnamed_addr #0 {
unreachable
}
```
The body of the function was deleted for a single `unreachable` llvm instruction.
When generating code, we obtain a main *without* any instruction, not even a `ret`.
Looking at object file generated, we can notice main is a 0 sized symbol, and "shares" same address than `never_called`, thus triggering this funny side effect.
```
$ readelf -s main.o
Symbol table '.symtab' contains 7 entries:
Num: Value Size Type Bind Vis Ndx Name
...
4: 0000000000000000 0 FUNC GLOBAL DEFAULT 2 main
5: 0000000000000000 12 FUNC GLOBAL DEFAULT 2 _Z12never_calledv
```
---
I didn't find any [absolute answer](https://stackoverflow.com/questions/2178115/are-compilers-allowed-to-eliminate-infinite-loops) on the fact a C++ compiler could optimize out an infinite loop with constant condition.
In our program, `clang` never removes the loop, but `clang++` does from O1.
This problem appeared in LLVM-13, and `git bisect` finds 6c3129549374c0e81e28fd0a21e96f8087b63a78.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs