41 ms·
GCC 4.9.2 seems to compile this: int test(int *x) { int *y = x; (*x)++; (*x)--; return (y - x); } into this at O3: test
by TheLoneWolfling 12y ago
GCC 4.9.2 seems to compile this:
int test(int *x) {
int *y = x;
(*x)++;
(*x)--;
return (y - x);
}
into this at O3:
test(int*):
xor eax, eax
ret
Effectively, into:
int test(int *x) {
return 0;
}
Which seems to contradict your adventure. I think it's because x cannot legally point to itself - x is an int ★, not a void ★. And you can't do arithmetic on a void ★, so it's not a problem there either.
- palunon 12y agoHere, GCC optimize it away. It's not required to do so. In fact, GCC can do whatever it wants in this case and still follow C standard. It may as well Yeah, you can't do x = &x. But since you didn't initialize x, it's initial value can be whatever is in memory at that particular time (or something else, nasal demons etc) If the particular value of x at runtime (there is no typechecks in C at runtime) happen to be &x, you can effectively get weird result. In fact, at -O0 : 000000000000000b <test>: b: 55 push %rbp c: 48 89 e5 mov %rsp,%rbp f: 48 89 7d e8 mov %rdi,-0x18(%rbp) 13: 48 8b 45 e8 mov -0x18(%rbp),%rax 17: 48 89 45 f8 mov %rax,-0x8(%rbp) 1b: 48 8b 45 e8 mov -0x18(%rbp),%rax 1f: 8b 00 mov (%rax),%eax 21: 8d 50 01 lea 0x1(%rax),%edx 24: 48 8b 45 e8 mov -0x18(%rbp),%rax 28: 89 10 mov %edx,(%rax) 2a: 48 8b 45 e8 mov -0x18(%rbp),%rax 2e: 8b 00 mov (%rax),%eax 30: 8d 50 ff lea -0x1(%rax),%edx 33: 48 8b 45 e8 mov -0x18(%rbp),%rax 37: 89 10 mov %edx,(%rax) 39: 48 8b 55 f8 mov -0x8(%rbp),%rdx 3d: 48 8b 45 e8 mov -0x18(%rbp),%rax 41: 48 29 c2 sub %rax,%rdx 44: 48 89 d0 mov %rdx,%rax 47: 48 c1 f8 02 sar $0x2,%rax 4b: 5d pop %rbp 4c: c3 retq
- TheLoneWolfling 12y agoI don't see what you're saying here. In C, it's undefined, so it's irrelevant. In my mythical language, the compiler is free to choose whatever initial value of x it wants. So your counterexample still doesn't work.
- oso2k 12y agoI think the real answer is that the DCE optimizer understands that y is assigned the same address in x, x never changes (after arithmetic cancels out), y never changes, and then the difference between y & x becomes 0.
- TheLoneWolfling 12y agoYep. And you can apply the same logic to the grandparent comment.