4 ms·
> define hidden i64 @foo.bar() { > entry: > %"$ret0" = alloca i64 > store i64 0, i64* %"$ret0" > store i64 1, i64* %"$ret0" > %"$ret0.ld.0" = load
by zeusk 9y ago
> define hidden i64 @foo.bar() {
> entry:
> %"$ret0" = alloca i64
> store i64 0, i64* %"$ret0"
> store i64 1, i64* %"$ret0"
> %"$ret0.ld.0" = load i64, i64* %"$ret0"
> ret i64 %"$ret0.ld.0"
> }
Can someone knowledgeable with Go, explain what's happening here? Why does it store a 0 and then a 1 in "$ret0"? Why does it allocate a single integer on the stack? (is it because this is just intermediate code for a virtual machine?) and all of that just to return a 1.
- loeg 9y ago> Why does it store a 0 Go language semantics define that variables receive a zero initialization.[0] > and then a 1 in "$ret0"? The 1 is because the code explicitly stores a 1 :-). Clearly the output code has not been through an optimization pass. [0]: https://gobyexample.com/variables https://gobyexample.com/variables
- zeusk 9y agobut if you look at the code, there isn't a "variable" to be initialized - the function is supposed to return a constant/literal one.
- barrkel 9y agoWhy zero first, that's already been explained. Why alloca from the stack: this is because there is a pass in LLVM which converts alloca locations into SSA form[1], and SSA is what many of the other optimizations in LLVM are built around. The rules around SSA mean that variables are renamed rather than modified (every assignment is final, except for phi nodes where control flow merges), so producing SSA output from an imperative language is a bit more difficult. Since LLVM comes with something that converts mutable stack allocations into SSA, it's easier to just leverage it. The pass is called mem2reg: http://llvm.org/docs/Passes.html#mem2reg-promote-memory-to-register http://llvm.org/docs/Passes.html#mem2reg-promote-memory-to-r... [1] https://en.wikipedia.org/wiki/Static_single_assignment_form https://en.wikipedia.org/wiki/Static_single_assignment_form