Skip to content

-O3: bounds checks in a loop over a Vec make it load the data pointer and the elements again on each step #4576

Backlog

Description

@hiraditya

At -O3, a loop over a Vec loads the data pointer of the Vec again on each step, and keeps the elements in memory. A check of the length before the loop removes both. It shows in n-body (#4381).

Reproduce

// Three points on a line pull each other. `step` runs `steps` steps over a Vec of 3 points.
import std::vec;

struct P {
  x : f64,
  v : f64,
}

impl Copy for P {}

fn step(ps : &mut Vec<P>, steps : i64) -> void {
  for _s in 0..steps {
    for i in 0..3 {
      for j in i + 1..3 {
        let d = ps.get(j).x - ps.get(i).x;
        ps[i].v = ps[i].v + d * 0.01;
        ps[j].v = ps[j].v - d * 0.01;
      }
    }
    for i in 0..3 {
      ps[i].x = ps[i].x + ps[i].v * 0.01;
    }
  }
}

fn main() -> i32 {
  let mut ps = Vec<P>::with_capacity(3);
  ps.push(P { x : 0.0, v : 0.0 });
  ps.push(P { x : 1.0, v : 0.0 });
  ps.push(P { x : 3.0, v : 0.0 });
  step(&mut ps, 1000);
  println!("{:.9} {:.9} {:.9}", ps.get(0).x, ps.get(1).x, ps.get(2).x);
  return 0;
}

Compile with vxc -O3 -c r1.vx -o r1.o, then read step in objdump -d --no-show-raw-insn -M intel r1.o. The second version adds if ps.len() != 3 { panic("three points"); } at the top of step. Both versions print 1.265859157 1.316464789 1.417676054.

step Loads of the length or the data pointer in the step loop Memory accesses in the step loop
As above 4, and 1 before the loop 29
With the length check 0, all before the loop 0

The step loop of the first version (rdi is ps):

15a: mov eax,DWORD PTR [rdi+0x8]   ; length, before the loop
170: test eax,eax ; jle panic       ; step loop starts
178: cmp eax,0x1  ; je  panic
181: mov rcx,QWORD PTR [rdi]       ; data pointer
     ... loads and stores of the points ...
1da: mov ecx,DWORD PTR [rdi+0x8]   ; length again, after the stores
1dd: cmp ecx,0x2 ; jl panic ; je panic
1e8: mov rcx,QWORD PTR [rdi]       ; data pointer again
     ... stores ...
211: mov rcx,QWORD PTR [rdi]       ; data pointer a third time
     ... loads and stores of every x and v ...
23f: dec rsi ; jne 170

Likely cause

The IR from vxc, put through mlir-translate and opt -O3 (LLVM 22), gives the same result. Two experiments on that IR (not repeated for this issue):

  1. The &mut Vec<P> parameter is ptr noalias, with no dereferenceable and no align. With align 8 dereferenceable(16), the data pointer and the length load once, before the loop. But the points still go through memory on each step (20 accesses). The bounds checks stay in the loop before the stores, so LICM cannot keep the points in registers.
  2. After -O3, one more function(loop-mssa(simple-loop-unswitch,licm),instcombine,simplifycfg) moves the checks out of the loop. Then the points stay in registers, with or without dereferenceable.

So the checks probably become loop-invariant only after LLVM fully unrolls the inner loops, and SimpleLoopUnswitch ran before that. Nobody checked this pass order with -print-after-all yet.

Cost in n-body

n-body on PR #4565, with n = 50000000, on one CPU of an Intel Xeon 6975P-C, 3 runs each:

n-body version Time
A loop over a Vec<Body> 1.73, 1.73, 1.74 s
The same, with a length check at the top 1.63, 1.61, 1.64 s
The bodies copied into local variables 1.50, 1.50, 1.51 s

With the length check, the loop has no memory access, but it is still slower than the version with local variables. The cause of that difference is not known.

Possible fixes

  • Give &T and &mut T parameters dereferenceable(<size of T>) and align(<alignment of T>). This removes the loads of the length and the data pointer.
  • Move the bounds checks out of the loop after full unrolling, for example with one more unswitch and LICM round. This keeps the elements in registers.

Until then, a check of the length before the loop is a workaround.

Generated With Claude Code

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions