Skip to content

Instantly share code, notes, and snippets.

@DocBohn
Created May 4, 2025 22:58
Show Gist options
  • Select an option

  • Save DocBohn/9b169749812f8f1218205fa9dd232a2f to your computer and use it in GitHub Desktop.

Select an option

Save DocBohn/9b169749812f8f1218205fa9dd232a2f to your computer and use it in GitHub Desktop.
Code demonstrating hand-crafted and compiler-generated migration of loop-invariant code out of the loop
void migration(int *destination, int const *source, int factor, int limit) {
for (int i = 0; i < limit; i++) {
destination[factor * limit + i] = source[i];
}
}
// -fmove-loop-invariants
migration:
mov w4, 0
mul w2, w3, w2
b .L2
.L3:
add w5, w2, w4
ldr w6, [x1, w4, sxtw 2]
str w6, [x0, w5, sxtw 2]
add w4, w4, 1
.L2:
cmp w4, w3
blt .L3
ret
void after_migration(int *destination, int const *source, int factor, int limit) {
int step = factor * limit;
for (int i = 0; i < limit; i++) {
destination[step + i] = source[i];
}
}
# -fmove-loop-invariants
migration:
movl $0, %eax
imull %ecx, %edx
jmp .L2
.L3:
leal (%rdx,%rax), %r8d
movslq %r8d, %r8
movslq %eax, %r9
movl (%rsi,%r9,4), %r9d
movl %r9d, (%rdi,%r8,4)
addl $1, %eax
.L2:
cmpl %ecx, %eax
jl .L3
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment