diff --git a/crates/metal2vulkan-air/src/canon/mod.rs b/crates/metal2vulkan-air/src/canon/mod.rs index 4cbe0a070..adab00a71 100644 --- a/crates/metal2vulkan-air/src/canon/mod.rs +++ b/crates/metal2vulkan-air/src/canon/mod.rs @@ -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)> = 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)?; diff --git a/crates/metal2vulkan-air/src/canon/tests/unrolling.rs b/crates/metal2vulkan-air/src/canon/tests/unrolling.rs index 56aba9ce0..852e8f6b0 100644 --- a/crates/metal2vulkan-air/src/canon/tests/unrolling.rs +++ b/crates/metal2vulkan-air/src/canon/tests/unrolling.rs @@ -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) -> Result { let mut m = ModuleBuilder::new(); let void = m.void(); @@ -106,7 +114,15 @@ fn counted(bound: Bound, ops: Ops, hints: Option) -> Result 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] diff --git a/crates/metal2vulkan-air/src/canon/unroll.rs b/crates/metal2vulkan-air/src/canon/unroll.rs index 2d14b5f4f..7b3bf8f88 100644 --- a/crates/metal2vulkan-air/src/canon/unroll.rs +++ b/crates/metal2vulkan-air/src/canon/unroll.rs @@ -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 { + scoped(m, |m, held| { + let mut live = filled(m, held, body.insts.len(), false)?; + let mut work: Vec = 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 = 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::()); + Ok(n) + }) +} + +/// Mark instruction `i` of [`live_size`] live and queue it, once. +fn mark(work: &mut Vec, 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, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8204a2c80..f18a03b44 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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 |