Hi all,
While reviewing Adds speaker notes to Compound Types section by rastringer · Pull Request #133 · google/comprehensive-rust · GitHub, I wanted to reproduce an optimization I believe Rust normally supports.
That is, I wanted to show that adding an assert!(n + 20 < a.len())
will remove the bounds checks in a function like this:
fn foo(n: usize, a: &[i32]) -> i32 {
let mut sum = 0;
for i in 0..20 {
sum += a[n + i];
}
sum
}
However, when trying to actually reproduce this on the Compiler Explorer, I don't see the diff I expect. I was hoping to see no comparisons in the function body after the assembly.
Now, I'm not very well-versed in assembly, but I believe I see a per-indexing comparison here:
example::foo:
push rax
mov rax, rdi
add rax, 20 ; <-- the assertion
jb .LBB0_3
cmp rax, rdx
jae .LBB0_2
cmp rdi, rdx
jae .LBB0_6
lea rcx, [rdi + 1]
cmp rcx, rdx ; <-- what is this?
jae .LBB0_7
mov eax, dword ptr [rsi + 4*rdi]
add eax, dword ptr [rsi + 4*rdi + 4]
jo .LBB0_47
lea rcx, [rdi + 2]
cmp rcx, rdx ; <-- what is this?
jae .LBB0_7
add eax, dword ptr [rsi + 4*rdi + 8]
jo .LBB0_47
lea rcx, [rdi + 3]
cmp rcx, rdx ; <-- what is this?
jae .LBB0_7
add eax, dword ptr [rsi + 4*rdi + 12]
jo .LBB0_47
lea rcx, [rdi + 4]
Am I reading the assembly wrong? I turned on -C opt-level=3
and -C overflow-checks
, but I still see the comparisons. What am I missing here?