FWIW, looking at an actual compiler, we see zero jumps (using a conditional move instead):
julia> function test(n)
i=0
while i<n
i += 1
end
return i
end
test (generic function with 1 method)
julia> @code_native test(10)
.text
Filename: REPL\[26\]
pushq %rbp
movq %rsp, %rbp
Source line: 3
xorl %eax, %eax
testq %rdi, %rdi
cmovnsq %rdi, %rax
Source line: 6
popq %rbp
retq
nop
edit: Sorry for the formatting. I don’t understand how source-code markup is supposed to work now?
edit2: Thanks, the markup works now!
edit3: So, to tie this into your greater point:
If you don’t ask “how would I code this in assembly” but rather “how should my compiler reason about this code”, then it is clear that the loop can be obviously eliminated: You place a phi-node at the end of the loop, and a tiny bit of inductive reasoning makes the loop body obviously dead code if n is an integer type. Slightly more magical (meaning I’m not a compiler expert) is the fact that the compiler (LLVM) can completely eliminate the following loop (replacing it with an explicit formula):
julia> function sumN6(lim)
s=0
i=0
while i<lim
i+=1
s+= i*i*i*i*i*i
end
return s
end
FWIW, looking at an actual compiler, we see zero jumps (using a conditional move instead):
edit: Sorry for the formatting. I don’t understand how source-code markup is supposed to work now?
edit2: Thanks, the markup works now!
edit3: So, to tie this into your greater point:
If you don’t ask “how would I code this in assembly” but rather “how should my compiler reason about this code”, then it is clear that the loop can be obviously eliminated: You place a phi-node at the end of the loop, and a tiny bit of inductive reasoning makes the loop body obviously dead code if n is an integer type. Slightly more magical (meaning I’m not a compiler expert) is the fact that the compiler (LLVM) can completely eliminate the following loop (replacing it with an explicit formula):
Source code markup is a bit broken. You should still be able to do it through greaterwrong’s comment editor though: https://www.greaterwrong.com/posts/MRqnYuCFHW46JPJag/understanding-is-translation