Optimizing away empty loop with step
Vladimir Panteleev
thecybershadow.lists at gmail.com
Fri Jul 30 09:58:01 UTC 2021
DMD [fails](https://issues.dlang.org/show_bug.cgi?id=22158) to
optimize away an empty for loop with an increment of 1. GDC and
LDC both succeed.
However, the results are more interesting if you make the step
variable:
```d
void fun(int a, int b, int step)
{
for (int i = a; i < b; i += step) {
}
}
```
The above code (valid C and D) compiles to an empty function with
clang and gcc:
https://godbolt.org/z/PnffvhecM
However, all three D compilers fail to optimize away the loop:
https://d.godbolt.org/z/r3MEGzoh1
Is the frontend doing something to prevent the loop from being
optimized away as in C?
My first guess was that the compiler refused to optimize it away
because it couldn't prove that the loop will ever exit. But, the
C compilers don't seem to have an issue with that.
My second guess was that the C compilers were happy with
optimizing it away because signed integer overflow is undefined
in C. But, changing the type to unsigned didn't make a difference.
https://godbolt.org/z/hMb83ne9d
More information about the digitalmars-d-ldc
mailing list