Keep an unrolled entry only where it comes out no larger than its loops

What: canonicalization runs the unrolling rounds (and the SCCP after
each) on a trial body and keeps it only where its size is at most the
entry's before unrolling; otherwise the loops stay as they were and
the trial's undefined-constant reads are dropped with it. The size is
`unroll::live_size`: the instructions that stay once unobserved code
is deleted (every one that is not pure, and every pure one those read,
directly or through others), not counting unconditional branches and
PHIs of one entry, which the copies leave where their blocks join.

Why: with the previous commit alone, a translation census of the
private corpus on the nvidia-rtx5080-laptop profile (no constants
supplied) grew 87 of the 15499 rows both builds translate and shrank
20: 83262314 words in all before the series, 84265507 after (+1.2%),
the largest growth 9546 -> 62171 words (6.5x) and 50185 -> 123245
(2.5x). Those loops' counters pick among a few cheap arms of a body
they run many times, so the copies add more than they decide away, and
the module is what the driver compiles. The fixture this item is for
still unrolls: `fold_loop_extract` specialized is 2296 words (the
baked form 2612). `engine/simd_divergent` `uniform_continue_k`, whose
38 golden cells the previous commit moved, now stays a loop and its
cells are as they were.

Not a speed-for-accuracy choice: either way the program computes the
same answers (unrolling copies every operation as it is), so
`docs/FAST-PATHS.md` has no row for it.

Tests: `canon::tests::unrolling` reworked: the switch's default arm is
80 operations, so copies taking the cheap arms are smaller than the
loop (unrolled, including at `TRIPS`), and copies taking the default
are larger (the loop stays, for supplied and for unsupplied lanes).

Verified: `cargo nextest run -p metal2vulkan-air -p metal2vulkan
--all-features -E 'package(metal2vulkan-air) |
test(/engine_arena|engine_specialized_folds|engine_simd_emulated|golden_hashes_match/)'`:
556 of 557 passed, golden_hashes failing only on the 380 new cells of
the fold fixtures (20 entries on 19 profiles) and no moved cell;
clippy on the crate with all targets and features.

(cherry picked from commit 8dc34fec499b1803bf13b0b1fe57ce1df8241f48)
(cherry picked from commit b1fe70ab5e41dbcf4d2879b7475b76aa1f5fc62c)
This commit is contained in:
Anees Iqbal committed 2026-11-03 00:45:19 -08:00
1 parent 568857fa6e
commit c7db26da1b
4 files changed
+135 -28

No files matched your search

+25 -6
View File
@@ -33,7 +33,8 @@
//! its initializer (`const_loads`); unreachable blocks are deleted. A value use of an unsupplied
//! constant that survives is `Error::NeedsInput(FunctionConstant)`. **Unrolling**: a loop whose
//! trip count SCCP made constant, and whose counter decides a branch of its body, is unrolled
//! within fixed ceilings, and SCCP runs again over the copies (`unroll`).
//! within fixed ceilings, and SCCP runs again over the copies; the result is kept where it is
//! no larger than the loops it replaces (`unroll`).
//! 8. **Post-check**: no unknown intrinsic, indirect call, or call to an undefined non-intrinsic
//! function survives, and no reachable branch tests `undef`. A table call's refused candidate,
//! a table call no linked function answers, and a function pointer used as a value are refused
@@ -599,17 +600,35 @@ pub fn specialize_dynamic(
body
};
// Loops whose trip count the constants decided, unrolled where their counters decide a branch
// of their body; SCCP after each round folds what the copies decide.
// of their body; SCCP after each round folds what the copies decide. The unrolled body is
// kept only where it comes out no larger than the loops it replaces (`unroll::live_size`).
let mut grown = 0;
let mut trial: Option<(Body, BTreeSet<u32>)> = None;
for _ in 0..unroll::ROUNDS {
let Some(unrolled) = unroll::round(&body, &mut parts, &mut grown, m)? else {
let current = trial.as_ref().map_or(&body, |(b, _)| b);
let Some(unrolled) = unroll::round(current, &mut parts, &mut grown, m)? else {
break;
};
body.release(m);
let solved = solve(&unrolled, &mut parts, &fcs, &name, m)?;
unrolled.release(m);
undefined_reads.extend(solved.reads);
body = solved.body;
let reads = match trial {
Some((old, mut reads)) => {
old.release(m);
reads.extend(solved.reads);
reads
}
None => solved.reads,
};
trial = Some((solved.body, reads));
}
if let Some((unrolled, reads)) = trial {
if unroll::live_size(&unrolled, m)? <= unroll::live_size(&body, m)? {
body.release(m);
body = unrolled;
undefined_reads.extend(reads);
} else {
unrolled.release(m);
}
}
matmul2d::refuse_left(&body, &parts, &ep.stage, &name, m)?;
post_check(&body, &parts, &stubs, &name, &control_points(ep), m)?;
@@ -1,5 +1,6 @@
//! Loops whose trip count the constants decide are unrolled where their counter decides a
//! branch of their body, and SCCP then folds what each iteration's copy decides.
//! branch of their body, and SCCP then folds what each iteration's copy decides; the unrolled
//! body is kept only where it is no larger than the loop.
use super::*;
use crate::ir::{LoopHints, Unroll};
@@ -24,10 +25,17 @@ enum Ops {
Run,
}
/// The operations of the default arm of [`counted`]'s switch: more than [`unroll::TRIPS`] copies
/// of one cheap case, so that a loop whose copies take the cheap cases is larger than its copies.
const HEAVY: u64 = 80;
/// The cheap opcodes the loops of these tests take.
const CHEAP: [u32; 4] = [1, 2, 2, 1];
/// A kernel whose loop runs `i` from 0 while `bound` holds, switching on lane `i & 3` of the
/// `<4 x i32>` opcodes `ops`: case 1 adds 3 to the accumulator, case 2 multiplies it by 5, any
/// other value xors it with 7. The accumulator starts from parameter 1's first word and is stored
/// to parameter 0. `hints` go on the latch.
/// other value applies [`HEAVY`] xors and adds. The accumulator starts from parameter 1's first
/// word and is stored to parameter 0. `hints` go on the latch.
fn counted(bound: Bound, ops: Ops, hints: Option<LoopHints>) -> Result<Entry, Error> {
let mut m = ModuleBuilder::new();
let void = m.void();
@@ -106,7 +114,15 @@ fn counted(bound: Bound, ops: Ops, hints: Option<LoopHints>) -> Result<Entry, Er
let b = f.bin(BinOp::Mul, acc, five);
f.br(latch);
f.switch_to(other);
let c = f.bin(BinOp::Xor, acc, seven);
let mut c = acc;
for k in 0..HEAVY {
c = if k % 2 == 0 {
f.bin(BinOp::Xor, c, seven)
} else {
let step = f.module().const_int(i32t, k);
f.bin(BinOp::Add, c, step)
};
}
f.br(latch);
f.switch_to(latch);
let next = f.push(
@@ -188,14 +204,14 @@ fn ops_of(text: &str) -> Vec<&str> {
#[test]
fn a_loop_whose_counter_indexes_a_constant_vector_is_unrolled_and_folded() {
// Six iterations over the lanes 1, 2, 9, 1, then 1, 2 again: the counter's lane decides each
// Six iterations over the lanes 1, 2, 2, 1, then 1, 2 again: the counter's lane decides each
// copy's switch, so straight-line code remains, the counter's own `add`s folded away.
let e = counted(Bound::Trips(6), Ops::Supplied([1, 2, 9, 1]), None).unwrap();
let e = counted(Bound::Trips(6), Ops::Supplied(CHEAP), None).unwrap();
let text = body_text(&e);
assert!(!text.contains("switch"), "{text}");
assert_eq!(
ops_of(&text),
["add", "mul", "xor", "add", "add", "mul"],
["add", "mul", "mul", "add", "add", "mul"],
"{text}"
);
}
@@ -204,33 +220,35 @@ fn a_loop_whose_counter_indexes_a_constant_vector_is_unrolled_and_folded() {
fn a_loop_past_the_ceilings_or_its_hints_stays_a_loop() {
// More iterations than the ceiling.
let trips = u64::from(unroll::TRIPS) + 1;
let text = body_text(&counted(Bound::Trips(trips), Ops::Supplied([1, 2, 9, 1]), None).unwrap());
let text = body_text(&counted(Bound::Trips(trips), Ops::Supplied(CHEAP), None).unwrap());
assert!(text.contains("switch"), "{text}");
// A trip count only the run knows.
let text = body_text(&counted(Bound::Run, Ops::Supplied([1, 2, 9, 1]), None).unwrap());
let text = body_text(&counted(Bound::Run, Ops::Supplied(CHEAP), None).unwrap());
assert!(text.contains("switch"), "{text}");
// `llvm.loop.unroll.disable` on the latch.
let hints = LoopHints {
unroll: Unroll::Disable,
must_progress: true,
};
let text =
body_text(&counted(Bound::Trips(4), Ops::Supplied([1, 2, 9, 1]), Some(hints)).unwrap());
let text = body_text(&counted(Bound::Trips(4), Ops::Supplied(CHEAP), Some(hints)).unwrap());
assert!(text.contains("switch"), "{text}");
// At the ceiling the loop is unrolled.
let trips = u64::from(unroll::TRIPS);
let text = body_text(&counted(Bound::Trips(trips), Ops::Supplied([1, 2, 9, 1]), None).unwrap());
let text = body_text(&counted(Bound::Trips(trips), Ops::Supplied(CHEAP), None).unwrap());
assert!(!text.contains("switch"), "{text}");
assert_eq!(ops_of(&text).len(), unroll::TRIPS as usize, "{text}");
}
#[test]
fn an_unsupplied_vector_unrolls_to_its_false_ways() {
// Undefined lanes read as zero at an index the loop's counter varies, so the switch stays a
// switch until unrolling makes each copy's index a constant: every copy takes the default.
let text = body_text(&counted(Bound::Trips(3), Ops::Unsupplied, None).unwrap());
assert!(!text.contains("switch"), "{text}");
assert_eq!(ops_of(&text), ["xor", "xor", "xor"], "{text}");
fn a_loop_whose_copies_would_be_larger_stays_a_loop() {
// Every copy would take the heavy default arm: three of them are larger than the loop, which
// stays, its switch with it. Undefined lanes read as zero, so an unsupplied vector is the
// same.
for ops in [Ops::Supplied([9, 9, 9, 9]), Ops::Unsupplied] {
let text = body_text(&counted(Bound::Trips(3), ops, None).unwrap());
assert!(text.contains("switch"), "{text}");
assert_eq!(ops_of(&text).len() as u64, HEAVY + 3, "{text}");
}
}
#[test]
+70 -1
View File
@@ -24,7 +24,10 @@
//!
//! Only the outermost qualifying loops are unrolled in a round; a loop nested in one is copied
//! with it, and the next round, after SCCP, takes each copy whose counter now decides its body.
//! There are at most [`ROUNDS`] rounds. Unrolling changes no operation: every instruction is copied
//! There are at most [`ROUNDS`] rounds. The body all rounds leave, folded, replaces the entry's
//! only where it is no larger ([`live_size`]): where what the copies decide removes less than the
//! copies add (a loop whose counter picks among a few cheap arms of a body it runs many times),
//! the loops stay, as the module is what the driver compiles. Unrolling changes no operation: every instruction is copied
//! as it is, with its flags, and runs as many times as before, so what the program computes is the
//! same. The ceilings bound only how large the copies may grow, which bounds the translation's
//! time and memory; a loop past them stays a loop and computes the same answers.
@@ -57,6 +60,72 @@ pub(super) const SLICE: u32 = 256;
/// No entry in a dense table.
const NONE: u32 = u32::MAX;
/// The size of `body` once nothing unobserved is left in it: every instruction that is not
/// [`super::sccp::is_pure`] (a store, a call, an atomic, a terminator), and every pure one such an
/// instruction reads, directly or through others, but for unconditional branches and PHIs of one
/// entry, which the copies of an unrolled loop leave where its blocks join. A pure value nothing
/// of those reads (a counter SCCP folded, an address no load uses any more) is not counted, as
/// the deletion of unobserved code removes it later.
pub(super) fn live_size(body: &Body, m: &mut Meter) -> Result<u64, Error> {
scoped(m, |m, held| {
let mut live = filled(m, held, body.insts.len(), false)?;
let mut work: Vec<InstId> = Vec::new();
for b in body.blocks.ids() {
for (i, inst) in body.block_insts(b) {
m.tick(1)?;
if !super::sccp::is_pure(&inst.kind) {
mark(&mut work, &mut live, i, m)?;
}
}
}
let mut n = 0u64;
let mut used: Vec<InstId> = Vec::new();
while let Some(i) = work.pop() {
m.tick(1)?;
let inst = body
.insts
.get(i)
.ok_or_else(|| invariant("instruction out of range"))?;
// A jump and a PHI of one entry are no work of their own: they go where blocks merge.
let copy = match &inst.kind {
InstKind::Br { .. } => true,
InstKind::Phi { incoming, .. } => incoming.len() == 1,
_ => false,
};
n += u64::from(!copy);
let mut count = 0;
inst.kind.for_each_value(|_| count += 1);
used.clear();
m.grow(&mut used, count)?;
inst.kind.for_each_value(|v| {
if let Value::Inst(u) = v {
used.push(u);
}
});
for &u in &used {
mark(&mut work, &mut live, u, m)?;
}
}
*held = held
.saturating_add((work.capacity() + used.capacity()) * std::mem::size_of::<InstId>());
Ok(n)
})
}
/// Mark instruction `i` of [`live_size`] live and queue it, once.
fn mark(work: &mut Vec<InstId>, live: &mut [bool], i: InstId, m: &mut Meter) -> Result<(), Error> {
match live.get_mut(i.index()) {
Some(seen) if !*seen => {
*seen = true;
m.grow(work, 1)?;
work.push(i);
Ok(())
}
Some(_) => Ok(()),
None => Err(invariant("instruction out of range")),
}
}
/// One loop to unroll.
struct Plan {
header: BlockId,
+4 -3
View File
@@ -11,8 +11,9 @@ metallib | AIR bitcode
── decode ──────► a typed AIR module and its ABI air::{bitstream, bitcode, ir, intrinsics, abi}
── specialize ──► one inlined entry: function constants baked, air::canon
constants propagated, loops of constant trip
count unrolled where that decides a branch,
linked functions resolved, pointee types erased
count unrolled where that decides a branch and
leaves the entry no larger, linked functions
resolved, pointee types erased
── analyze ─────► MemoryPlan: provenance, one representation memory
per value, slot windows
── select ──────► Plan: a strategy per instruction and interface lower::select, lower::strategy
@@ -66,7 +67,7 @@ rest is `crates/metal2vulkan/src/`.
| Module | Role |
|---|---|
| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining, function constants, SCCP (reading the integer fields of a constant global whose value is known), the unrolling of loops whose constant trip count decides a branch, devirtualization, linking, pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, and the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data |
| `air` (`metal2vulkan-air`) | The container (metallib, bitcode wrapper, raw module), the bitstream and bitcode readers, the typed IR, the `air.*` and `llvm.*` intrinsic families, the metadata ABI (`AirAbi`), and canonicalization (`canon`: inlining, function constants, SCCP (reading the integer fields of a constant global whose value is known), the unrolling of loops whose constant trip count decides a branch where that leaves the entry no larger, devirtualization, linking, pruning, pointee erasure, the speculation of the short branch arms Metal's backend runs in every lane, and the split of a whole array's or struct's load or store in buffer or threadgroup memory into its members' accesses). Canonicalization also writes the formats the binder and runtime read: the visible-function table's words and the rasterization-rate map's parameter data |
| `graph` | The shared RPO, dominator tree, loop forest and SCC |
| `budget` | `Budget`, `CancelToken`, and the per-attempt `Meter`: deadline, cancellation, work units, the byte ledger and every structural cap |
| `memory/` | Pointer provenance, the `MemoryPlan`, leaf access emitters, arenas, root and handle lookups, word composition, atomics |