un-requested compiler optimisations
David Nadlinger
see at klickverbot.at
Thu Apr 14 12:17:12 PDT 2011
On 4/14/11 8:24 PM, spir wrote:
> If it does optimise, then it is definitely a compiler bug. Since you
> *explicitely* ask for a double reverse, it *must* just do it.
> Suppressing them is here just breaking the language's semantics!
> […]
Sigh… First, as Steve already pointed out, retro() specifically
shortcuts reversing a range twice to the original range.
Second, your remarks about optimization are not quite correct, at least
for most of today's high-level languages. A compiler is free to optimize
a program in whatever possible way, as long as it can prove the result
equivalent to the original. And as burning CPU-cycles is not part of the
program semantics, a modern optimizing compiler is free to optimize the
loop and factorial call away altogether. If you don't believe me, have a
look at the attached sample program and the asm generated for main()
(some recent Clang version, clang -O3).
David
---
#include <stdio.h>
int factorial(int a) {
int p = 1;
for (int i = 2; i <= a; ++i) {
p *= i;
}
return p;
}
int main (int argc, char const *argv[]) {
int t;
for (long i = 0; i < 10000000; ++i) {
t = factorial(9);
}
printf("%d\n", t);
return 0;
}
_main:
0000000100000ee0 pushq %rbp
0000000100000ee1 movq %rsp,%rbp
0000000100000ee4 leaq 0x00000041(%rip),%rdi
0000000100000eeb movl $0x00058980,%esi ; 9! in hex
0000000100000ef0 xorb %al,%al
0000000100000ef2 callq 0x100000f02; symbol stub for: _printf
0000000100000ef7 xorl %eax,%eax
0000000100000ef9 popq %rbp
0000000100000efa ret
More information about the Digitalmars-d-learn
mailing list