3 ms·
> I've never seen a compiler do it. Oh I have. Often. https://godbolt.org/z/PM9herj3P https://godbolt.org/z/PM9herj3P Note: these could be tail-calls, and ar
by brucehoult 1y ago
> I've never seen a compiler do it.
Oh I have. Often.
https://godbolt.org/z/PM9herj3P https://godbolt.org/z/PM9herj3P
Note: these could be tail-calls, and are if you use `-O2` or `-Os`, but that's not important. Make it `foo(n) + 13` and you still get the "don't make a stack frame unless needed" optimisation.
Oh, here's an interesting one. Arm proactively pushes everything, x86 and RISC-V only if `err()` will be called.
https://godbolt.org/z/93WEbc1q9 https://godbolt.org/z/93WEbc1q9
I also would expect the number of function executions which are dynamically leaf functions [1] to be greater than 50%. Except for the kind of perverse call chains you get in Java and perhaps some other OO code bases where there are huge numbers of layers of abstraction where each method simply calls one other lower level method.
[1] i.e. that don't call another function on that execution, though in other circumstances they could.
- kragen 1y agoShows what I know! I appreciate the correction. I wonder why the second example frustrates the optimization—but only on ARM? Also, why is it pushing r0 and r1? That's stupid. It's also stupid that it's using an extra `add` instruction to un-push them—if it doesn't want to overwrite r0, it could pop the worthlessly pushed values into r1 and r2, or r3 and r4. I tried a bunch of different versions of GCC on your example code, and they all seem to produce code that's bad in obvious ways, but they're different obvious ways.
- kragen 1y agoIn further thought, if you have an instruction cache, adding 8 to SP is a faster way to discard the two useless values than popping them into unused registers. So that part is arguably defensible. But why push them? There can't be a requirement for a 16-byte-aligned stack pointer at all times—the add would violate it.
- brucehoult 1y agoIt's definitely strange. And arm64 does it like the others.