by SkiFire13 · 1y ago · 0 comments
In lower level languages there are also a bunch of other issues:
- RAII can easily make functions that appear in a tail position not actually tail calls, due to destructors implicitly running after the call;
- there can be issues when reusing the stack frame of the caller, especially with caller-cleanup calling conventions;
- the compiler needs to prove that no pointers to the stack frame of the function being optimized have escaped, otherwise it would be reusing the memory of live variables which is illegal.
That is a common criticism. You're referring to the functional programmers. They would typically argue that building up state based on transient loop variables is a mistake. The body of a loop ideally should be (at the time any stack trace gets thrown) a pure function of constant values and a range that is being iterated over while being preserved. That makes debugging easier.
In a couple languages I've seen proposals to solve this problem with a syntactic opt-in for tail call elimination, though I'm not sure whether any mainstream language has actually implemented this.
https://crates.io/crates/tiny_tco
As an optimization my understanding is that GCC and LLVM implement it so Rust, C, and C++ also have it implicitly as optimizations that may or may not apply to your code.
But yes, zig does have a formal language syntax for guaranteeing tail calls to happen at the language level (which I agree with as the right way to expose this optimization).
I did not know that! But I am a bit confused, since I don't really program in either language. Where exactly in the documentation could I read more about this? Or see more examples?
The language reference for @call[0] was quite unhelpful for my untrained eye.
[1]: https://github.com/ziglang/zig/issues/694#issuecomment-15674... [2]: https://github.com/llvm/llvm-project/issues/54964 [3]: https://github.com/rust-lang/rfcs/pull/3407
> All current mainstream compilers perform tail call optimisation fairly well (and have done for more than a decade)
https://stackoverflow.com/questions/34125/which-if-any-c-com... (2008)
You can now get a guarantee by using non-standard compiler attributes:
https://clang.llvm.org/docs/AttributeReference.html#musttail
https://gcc.gnu.org/onlinedocs/gcc/Statement-Attributes.html...
https://ocaml.github.io/ocamlunix/ocamlunix.html
MirageOS
House OS,
https://programatica.cs.pdx.edu/House/
Just saying.