From 0ac159bd6f1ecd2bd4655ec3a42810da4f4eec50 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 31 Aug 2026 11:34:38 +0300 Subject: [PATCH] Nest reducible control flow instead of flattening it to a state machine The nesting structurizer now expresses everything the fragment shader in bugs/fragment-code-size-explosion needs, so that module no longer reaches the driver as one dispatch state machine. Three things were missing. Staged exits. SPIR-V lets a block leave the construct it is in and no further, but `while (c) { if (d) { p(); if (e) break; } q(); }` leaves a selection and a loop on one edge. Such an edge now records its destination in one function-scope flow variable and leaves the innermost construct; each construct it crosses carries a dispatch at its merge that either enters its own continuation at the named destination or forwards through that dispatch's merge block, which sits directly inside the next construct out. An analysis pass decides which constructs need a dispatch, so a construct no staged edge crosses and with one way out keeps a plain merge and never touches the variable. Switch constructs. A divergent terminator declares a selection of its own, and SPIR-V allows breaking out of a nested construct only to an enclosing loop or switch -- never to an enclosing selection. The analysis marks the dispatches this applies to and they are written as OpSwitch. Dispatch headers and arm entries. A dispatch entered from an enclosing construct rather than fused into one terminator now gets a header of its own, which is what gives it a merge block its arms' nested constructs may break to; and an arm is a shape, not a block, so a loop arm is entered at its synthesized header rather than at the original block. The latter was producing a back edge into a loop body that bypassed the header. Measured on that shader (release, 2.4s, unchanged): function-scope variables 3516 -> 951 widest OpSwitch 1024 -> 122 total switch cases 2286 -> 608 OpLoopMerge 0 -> 168 emitted words 249063 -> 199869 The count that mattered is the first: the driver's compile went unbounded promoting thousands of variables back to SSA inside one loop that held the whole program. There are now 168 real nested loops and no whole-function dispatch. Verified: spirv-val vulkan1.2 passes on the emitted module; 12 nesting tests including a new end-to-end pin for the two-construct break; full 1681-test product suite green; fmt, workspace clippy with -D warnings and all-features Rustdoc clean. --- src/native/reloop_nest/emit.rs | 1070 ++++++++++++++++++++++--------- src/native/reloop_nest/mod.rs | 52 ++ src/native/reloop_nest/shape.rs | 36 +- 3 files changed, 848 insertions(+), 310 deletions(-) diff --git a/src/native/reloop_nest/emit.rs b/src/native/reloop_nest/emit.rs index 302133439..42645c54d 100644 --- a/src/native/reloop_nest/emit.rs +++ b/src/native/reloop_nest/emit.rs @@ -1,16 +1,30 @@ //! SPIR-V emission for the nesting structurizer. //! -//! Walks the [`Shape`](super::shape::Shape) tree and writes the nested loop / selection constructs -//! it describes. The point of the nesting is what it does NOT do: it keeps every value in SSA, -//! because the shape tree preserves the original CFG's paths and therefore its dominance. Only -//! `OpPhi` results are register-demoted, because a phi's predecessor identity is what the nesting -//! rewrites. +//! Walks the [`Shape`](super::shape::Shape) tree and writes the nested loop and selection +//! constructs it describes. The point of the nesting is what it does NOT do: it keeps every value +//! in SSA, because the shape tree preserves the original CFG's paths and therefore its dominance. +//! Only `OpPhi` results are register-demoted, because a phi's predecessor identity is exactly what +//! nesting rewrites. //! -//! Contrast with the state-machine constructor in `super::super::relooper`, which makes every block -//! a sibling switch case and so has to demote every value that crosses a block boundary. On a large -//! function that produces one loop containing the whole program plus thousands of function-scope -//! variables — a shape that is valid, but that drives a driver's SSA reconstruction and register -//! allocator superlinear. +//! # Leaving more than one construct +//! +//! SPIR-V lets a block leave the construct it is in, and no further: a branch out has to target +//! that construct's own merge block, the innermost enclosing loop's continue target, or a +//! `return`-like terminator. Real control flow needs more than that — `while (c) { if (d) { p(); +//! if (e) break; } q(); }` leaves a selection AND a loop on one edge. +//! +//! Such an edge is staged. It records its destination in one function-scope flow variable and +//! leaves the innermost construct. Every construct it has to pass through carries a dispatch at its +//! merge that reads the variable, enters its own continuation when the destination belongs to it, +//! and otherwise forwards through the dispatch's merge block — which sits directly inside the next +//! construct out, so forwarding one more level is an ordinary branch to that construct's merge. The +//! analysis pass decides which constructs need a dispatch; a construct no staged edge crosses, and +//! whose body leaves for a single destination, keeps a plain merge and never touches the variable. +//! +//! Contrast the state-machine constructor in `super::super::relooper`, which makes every block a +//! sibling switch case and so must demote every value that crosses a block boundary. On a large +//! function that yields one loop containing the whole program plus thousands of function-scope +//! variables — valid SPIR-V, and a shape a driver's compiler can take unbounded time on. //! //! Anything this emitter cannot express is returned as `Err`, and the caller keeps the function on //! the state-machine constructor. It never emits a guess. @@ -22,51 +36,88 @@ use spirv::{LoopControl, Op, SelectionControl, StorageClass, Word}; use std::collections::{BTreeSet, HashMap, HashSet}; /// What a branch to some original block becomes in the emitted nesting. -enum Action { - /// Branch straight at a label: an arm entry, the next shape's start, a construct merge, or a +struct Action { + /// The label to branch to: an arm entry, the continuation's start, a construct merge, or a /// loop's continue target. - Goto(Word), - /// Same, but the destination is a dispatch that reads the flow variable, so the edge has to say - /// which entry it meant first. - Dispatch { label: Word, flow: u64 }, + label: Word, + /// The destination to record in the flow variable first, when the construct that handles this + /// branch reads it. + flow: Option, } -/// One enclosing SPIR-V construct. Resolution walks this stack outward to classify a branch. +/// One enclosing construct, as the emitter sees it. struct Frame { - /// Continue targets: the original loop entry labels. Empty for a selection frame. + /// The shape this construct came from, so resolution can consult its facts. + id: usize, + /// The original loop entry labels, for a loop frame; empty for a selection frame. loop_entries: BTreeSet, continue_label: Option, + /// Where a branch leaving this construct goes. merge_label: Word, - /// The original labels reachable by leaving this construct through its merge. + /// The original labels this construct's continuation can be entered at. next_entries: BTreeSet, - /// Whether the merge block is a flow dispatch rather than a single continuation. - merge_dispatches: bool, + /// Whether the merge carries a flow dispatch, so edges leaving here name a destination. + dispatches: bool, +} + +/// What the analysis pass learned about one construct. +#[derive(Default)] +struct ConstructFacts { + /// The destinations branches inside this construct leave it for. + destinations: BTreeSet, + /// Whether a staged edge bound for an outer construct passes through this one. + forwards: bool, + /// Whether some block nested in a further construct leaves this one. SPIR-V lets a nested + /// construct break to an enclosing loop or switch, never to an enclosing selection, so a + /// dispatch marked here has to be written as `OpSwitch` even when two arms would read as an + /// ordinary conditional. + needs_switch: bool, +} + +impl ConstructFacts { + fn needs_dispatch(&self) -> bool { + self.forwards || self.destinations.len() > 1 + } +} + +/// A construct as the analysis pass sees it: the same stack, without any emitted labels. +struct AnalysisFrame { + id: usize, + loop_entries: BTreeSet, + next_entries: BTreeSet, + is_loop: bool, } pub(super) struct Emitter<'a, 'b> { tc: &'a mut TypeCtx<'b>, blocks: HashMap, terms: HashMap, - /// Phi result id -> (variable, result type). - phi_var: HashMap, - /// Original block -> the phi entries it must load on entry. + /// Original block -> the phi results it must load on entry, as (result, variable, type). phi_loads: HashMap>, /// (predecessor, block) -> the values that edge carries into the block's phis. phi_stores: HashMap<(Word, Word), Vec<(Word, Word)>>, flow_var: Option, flow_ty: Word, flow_id: HashMap, - /// Shape id -> the label its emission starts at. - start: HashMap, - /// Multiple shapes entered from exactly one terminator, so no dispatch block is needed. + facts: HashMap, + /// Shape id -> the label a branch enters that shape at, for shapes with a single entry. + head: HashMap, + /// Construct shape id -> its merge label. + merge: HashMap, + /// Constructs whose plain merge is a dispatch header, so edges leaving them record their + /// destination even though the construct itself does not dispatch. + merge_flow: HashSet, + /// Multiple shapes entered by one terminator, so no dispatch block selects their arms. fused: HashSet, + /// Constructs whose merge must be a block of its own even when one destination would do. A + /// dispatch header's merge has to be dominated by that header, so it cannot be a label the + /// enclosing construct also branches straight at. + forced_dispatch: HashSet, variables: Vec, out: Vec, } -/// Rebuild `function`'s blocks as nested structured control flow. Returns `Err` with a short reason -/// when the shape tree contains something this emitter does not express; the function is left -/// untouched in that case. +/// Rebuild `function`'s blocks as nested structured control flow. pub(super) fn structure_function( function: &Function, graph: &Graph, @@ -78,24 +129,28 @@ pub(super) fn structure_function( tc, blocks: HashMap::new(), terms: HashMap::new(), - phi_var: HashMap::new(), phi_loads: HashMap::new(), phi_stores: HashMap::new(), flow_var: None, flow_ty, flow_id: HashMap::new(), - start: HashMap::new(), + facts: HashMap::new(), + head: HashMap::new(), + merge: HashMap::new(), + merge_flow: HashSet::new(), fused: HashSet::new(), + forced_dispatch: HashSet::new(), variables: Vec::new(), out: Vec::new(), }; emitter.index(function)?; - emitter.plan(shape, true); + emitter.plan(shape, true)?; + emitter.analyze(shape, graph, &mut Vec::new())?; + emitter.assign_merges(shape)?; emitter.demote_phis(graph)?; - let entry_label = emitter.start_of(shape); - let mut stack = Vec::new(); - emitter.emit(shape, &mut stack)?; + let entry_label = emitter.head_of(shape)?; + emitter.emit(shape, &mut Vec::new())?; // OpVariable is only legal in a function's first block, and the root shape may be a loop // header, so the hoisted declarations get a prologue of their own. @@ -120,6 +175,8 @@ pub(super) fn structure_function( } impl Emitter<'_, '_> { + // ---------------------------------------------------------------- indexing + fn index(&mut self, function: &Function) -> Result<(), String> { for block in &function.blocks { let label = block_label(block).ok_or_else(|| "block without a label".to_string())?; @@ -133,11 +190,14 @@ impl Emitter<'_, '_> { // OpVariable is only legal in a function's first block, and nesting can put any block // inside a loop. Hoist the declarations into the prologue this emitter always writes. let mut kept = Vec::with_capacity(block.instructions.len()); - for instruction in block.instructions.drain(..) { - if instruction.class.opcode == Op::Variable { - self.variables.push(instruction); - } else { - kept.push(instruction); + for instruction in std::mem::take(&mut block.instructions) { + match instruction.class.opcode { + Op::Variable => self.variables.push(instruction), + // The incoming module already carries merge declarations for whatever structure + // it had. This pass derives the structure again, and a stale declaration would + // no longer sit immediately before the branch it belongs to. + Op::SelectionMerge | Op::LoopMerge => {} + _ => kept.push(instruction), } } block.instructions = kept; @@ -146,62 +206,347 @@ impl Emitter<'_, '_> { Ok(()) } - /// Assign a start label to every shape and decide which dispatches can be fused away. - /// - /// A `Multiple` needs a dispatch block only when more than one terminator can enter it. That is - /// exactly when it follows a `Loop` or another `Multiple`: after a `Simple`, the single - /// preceding block's own terminator selects the arm, so the branch goes straight to the arm and - /// the flow variable is never involved. - fn plan(&mut self, shape: &Shape, single_predecessor: bool) { + /// Assign the label a branch enters each shape at, and record which dispatches fuse away. + fn plan(&mut self, shape: &Shape, single_predecessor: bool) -> Result<(), String> { match shape { Shape::Simple { id, label, next } => { - self.start.insert(*id, *label); + self.head.insert(*id, *label); if let Some(next) = next { - self.plan(next, true); + self.plan(next, true)?; + } + } + Shape::Loop { + id, + entries, + inner, + next, + } => { + if entries.len() != 1 { + return Err("loop with several entries".to_string()); + } + let header = self.tc.fresh(); + self.head.insert(*id, header); + self.plan(inner, true)?; + if let Some(next) = next { + self.plan(next, false)?; + } + } + Shape::Multiple { + id, handled, next, .. + } => { + if handled.is_empty() { + return Err("dispatch with no arms".to_string()); + } + // After a `Simple` the single preceding terminator selects the arm itself, so the + // dispatch fuses into it. After a construct the arms are selected by that + // construct's own merge dispatch, and this shape occupies no block of its own. + if single_predecessor { + self.fused.insert(*id); + } else { + // Entered from an enclosing construct's dispatch, so it needs a header of its + // own: that header is what makes it a switch construct with a merge block + // nested constructs inside its arms are allowed to break to. + let header = self.tc.fresh(); + self.head.insert(*id, header); + self.forced_dispatch.insert(*id); + } + for (_, arm) in handled { + self.plan(arm, true)?; + } + if let Some(next) = next { + self.plan(next, false)?; + } + } + } + Ok(()) + } + + fn head_of(&self, shape: &Shape) -> Result { + self.head + .get(&shape.id()) + .copied() + .ok_or_else(|| "shape has no single entry".to_string()) + } + + // ---------------------------------------------------------------- analysis + + /// Classify every branch against the constructs enclosing it, recording per construct which + /// destinations its body leaves for and whether staged edges pass through it. + fn analyze( + &mut self, + shape: &Shape, + graph: &Graph, + stack: &mut Vec, + ) -> Result<(), String> { + match shape { + Shape::Simple { label, next, .. } => { + let local = next.as_ref().map(|next| next.entry_labels()); + let targets = graph.succ(*label).to_vec(); + let divergent = targets.len() > 1; + for target in targets { + if local.as_ref().is_some_and(|local| local.contains(&target)) { + if let Some(next) = next { + self.route(next, target); + } + continue; + } + self.classify(target, divergent, stack)?; + } + if let Some(next) = next { + self.analyze(next, graph, stack)?; + } + } + Shape::Loop { + id, + entries, + inner, + next, + } => { + stack.push(AnalysisFrame { + id: *id, + loop_entries: entries.clone(), + next_entries: next + .as_ref() + .map(|next| next.entry_labels()) + .unwrap_or_default(), + is_loop: true, + }); + let result = self.analyze(inner, graph, stack); + stack.pop(); + result?; + if let Some(next) = next { + self.route_destinations(*id, next); + self.analyze(next, graph, stack)?; + } + } + Shape::Multiple { + id, handled, next, .. + } => { + stack.push(AnalysisFrame { + id: *id, + loop_entries: BTreeSet::new(), + next_entries: next + .as_ref() + .map(|next| next.entry_labels()) + .unwrap_or_default(), + is_loop: false, + }); + let mut result = Ok(()); + for (_, arm) in handled { + result = self.analyze(arm, graph, stack); + if result.is_err() { + break; + } + } + stack.pop(); + result?; + if let Some(next) = next { + self.route_destinations(*id, next); + self.analyze(next, graph, stack)?; + } + } + } + Ok(()) + } + + fn route_destinations(&mut self, id: usize, next: &Shape) { + let destinations = self + .facts + .get(&id) + .map(|facts| facts.destinations.iter().copied().collect::>()) + .unwrap_or_default(); + for destination in destinations { + self.route(next, destination); + } + } + + /// Record `target` on every dispatch it has to pass through to reach where it is rendered. A + /// dispatch owns each of its entries, but an entry whose region is shared with another owns no + /// arm: reaching it means leaving the dispatch again through its merge, which therefore has to + /// know about it. + fn route(&mut self, shape: &Shape, target: Word) { + let Shape::Multiple { + id, handled, next, .. + } = shape + else { + return; + }; + if handled.iter().any(|(label, _)| *label == target) { + return; + } + self.facts + .entry(*id) + .or_default() + .destinations + .insert(target); + if let Some(next) = next { + self.route(next, target); + } + } + + fn classify( + &mut self, + target: Word, + divergent: bool, + stack: &[AnalysisFrame], + ) -> Result<(), String> { + // A continue may cross selections, but only reaches the innermost enclosing loop; + // continuing an outer loop is not expressible as one structured branch. + if let Some(innermost_loop) = stack.iter().rev().find(|frame| frame.is_loop) { + if innermost_loop.loop_entries.contains(&target) { + return Ok(()); + } + } + if stack + .iter() + .any(|frame| frame.loop_entries.contains(&target)) + { + return Err("branch continues an outer loop".to_string()); + } + let Some(depth) = stack + .iter() + .rposition(|frame| frame.next_entries.contains(&target)) + else { + return Err("branch target is outside every enclosing construct".to_string()); + }; + self.facts + .entry(stack[depth].id) + .or_default() + .destinations + .insert(target); + for frame in &stack[depth + 1..] { + self.facts.entry(frame.id).or_default().forwards = true; + } + if divergent { + // A divergent terminator declares a selection of its own, so this edge leaves that + // selection as well as the construct around it. Only a loop or a switch may be broken + // out of from inside a nested construct. + if let Some(innermost) = stack.last() { + self.facts.entry(innermost.id).or_default().needs_switch = true; + } + } + Ok(()) + } + + // ------------------------------------------------------------ merge labels + + /// Give every construct its merge label, now that the analysis says whether it dispatches. + fn assign_merges(&mut self, shape: &Shape) -> Result<(), String> { + match shape { + Shape::Simple { next, .. } => { + if let Some(next) = next { + self.assign_merges(next)?; } } Shape::Loop { id, inner, next, .. } => { - let header = self.tc.fresh(); - self.start.insert(*id, header); - self.plan(inner, true); + // The continuation is assigned first: a plain merge names a label inside it. if let Some(next) = next { - self.plan(next, false); + self.assign_merges(next)?; } + self.assign_construct_merge(*id, next.as_deref())?; + self.assign_merges(inner)?; } - Shape::Multiple { id, handled, next } => { - if single_predecessor && !handled.is_empty() { - self.fused.insert(*id); - // A fused dispatch starts wherever its continuation does; the arms are branched - // to directly, so the shape itself never occupies a block. - let label = match next { - Some(next) => { - self.plan(next, false); - self.start_of(next) - } - None => self.fresh_unreachable(), - }; - self.start.insert(*id, label); - } else { - let dispatch = self.tc.fresh(); - self.start.insert(*id, dispatch); - if let Some(next) = next { - self.plan(next, false); - } + Shape::Multiple { + id, handled, next, .. + } => { + if let Some(next) = next { + self.assign_merges(next)?; } + self.assign_construct_merge(*id, next.as_deref())?; for (_, arm) in handled { - self.plan(arm, true); + self.assign_merges(arm)?; } } } + Ok(()) } - fn start_of(&self, shape: &Shape) -> Word { - self.start - .get(&shape.id()) + fn assign_construct_merge(&mut self, id: usize, next: Option<&Shape>) -> Result<(), String> { + let dispatches = self.dispatches(id); + let destination = self + .facts + .entry(id) + .or_default() + .destinations + .iter() .copied() - .expect("every shape was planned") + .next(); + let label = if dispatches { + self.tc.fresh() + } else { + match (destination, next) { + // One way out: the merge is simply where that destination is rendered, so the + // construct's body branches straight at it. + (Some(destination), Some(next)) => { + let (label, needs_flow) = self.entry_label(next, destination)?; + if needs_flow { + self.merge_flow.insert(id); + } + label + } + // Nothing leaves this construct normally; its declared merge is unreachable. + _ => self.fresh_unreachable(), + } + }; + self.merge.insert(id, label); + Ok(()) + } + + /// Where a branch enters `shape` at `target`, which must be one of its entries, and whether + /// the edge has to record `target` in the flow variable first — which it does exactly when the + /// label is a dispatch header that reads the variable to pick its arm. + fn entry_label(&self, shape: &Shape, target: Word) -> Result<(Word, bool), String> { + match shape { + Shape::Simple { label, .. } if *label == target => Ok((*label, false)), + Shape::Loop { entries, id, .. } if entries.contains(&target) => self + .head + .get(id) + .copied() + .map(|header| (header, false)) + .ok_or_else(|| "loop without a header".to_string()), + Shape::Multiple { + id, handled, next, .. + } => { + if !self.fused.contains(id) { + // Every entry goes through the header: an arm is one of its cases, and anything + // further on leaves again through the dispatch at this construct's merge. Making + // it the single way in is what keeps the header dominating its own merge. + return self + .head + .get(id) + .copied() + .map(|header| (header, true)) + .ok_or_else(|| "dispatch without a header".to_string()); + } + if let Some((_, arm)) = handled.iter().find(|(label, _)| *label == target) { + // The arm is a shape, not a block: when it is a loop, control enters at the + // loop header this emitter synthesized, never at the original block. + return Ok((self.head_of(arm)?, false)); + } + match next { + Some(next) => self.entry_label(next, target), + None => Err("destination is not an entry of the continuation".to_string()), + } + } + _ => Err("destination is not an entry of the continuation".to_string()), + } + } + + fn merge_of(&self, id: usize) -> Result { + self.merge + .get(&id) + .copied() + .ok_or_else(|| "construct without a merge".to_string()) + } + + fn dispatches(&self, id: usize) -> bool { + self.forced_dispatch.contains(&id) + || self + .facts + .get(&id) + .is_some_and(ConstructFacts::needs_dispatch) } /// A block that exists only to be a declared merge no path reaches. @@ -216,21 +561,26 @@ impl Emitter<'_, '_> { label } + // ------------------------------------------------------------------- phis + /// Replace every `OpPhi` with a function-scope variable: the incoming edges store, the block /// loads. The nesting rewrites which block physically branches into a merge, so a phi's /// predecessor list is the one thing it cannot carry through unchanged. fn demote_phis(&mut self, graph: &Graph) -> Result<(), String> { let labels = self.blocks.keys().copied().collect::>(); for label in labels { - let Some(block) = self.blocks.get(&label) else { - continue; - }; - let phis = block - .instructions - .iter() - .filter(|inst| inst.class.opcode == Op::Phi) - .cloned() - .collect::>(); + let phis = self + .blocks + .get(&label) + .map(|block| { + block + .instructions + .iter() + .filter(|inst| inst.class.opcode == Op::Phi) + .cloned() + .collect::>() + }) + .unwrap_or_default(); if phis.is_empty() { continue; } @@ -249,7 +599,6 @@ impl Emitter<'_, '_> { Some(var), vec![Operand::StorageClass(StorageClass::Function)], )); - self.phi_var.insert(result, (var, ty)); self.phi_loads .entry(label) .or_default() @@ -261,7 +610,7 @@ impl Emitter<'_, '_> { else { return Err("phi operand shape".to_string()); }; - // Unreachable predecessors keep no edge in the emitted nesting. + // A predecessor no path reaches keeps no edge in the emitted nesting. if graph.successors.contains_key(predecessor) { self.phi_stores .entry((*predecessor, label)) @@ -280,6 +629,8 @@ impl Emitter<'_, '_> { Ok(()) } + // -------------------------------------------------------------- resolution + fn flow_variable(&mut self) -> Word { if let Some(var) = self.flow_var { return var; @@ -301,9 +652,8 @@ impl Emitter<'_, '_> { *self.flow_id.entry(label).or_insert(next) } - /// Where a branch to `target` goes, given the constructs currently open. `local` is the shape - /// that follows the block being emitted; its entries are reached by falling through rather than - /// by leaving a construct. + /// Where a branch to `target` goes. `local` is the shape that follows the block being emitted: + /// its entries are reached by falling through, without leaving any construct. fn resolve( &mut self, target: Word, @@ -311,82 +661,71 @@ impl Emitter<'_, '_> { stack: &[Frame], ) -> Result { if let Some(local) = local { - if let Some(action) = self.enter(target, local)? { - return Ok(action); + if local.entry_labels().contains(&target) { + return self.enter(local, target); } } - for (depth, frame) in stack.iter().enumerate().rev() { - let innermost = depth + 1 == stack.len(); + if let Some(frame) = stack + .iter() + .rev() + .find(|frame| frame.continue_label.is_some()) + { if frame.loop_entries.contains(&target) { - if !innermost { - return Err("branch continues an outer loop".to_string()); - } let label = frame .continue_label .ok_or_else(|| "loop frame without a continue target".to_string())?; - return Ok(Action::Goto(label)); - } - if frame.next_entries.contains(&target) { - if !innermost { - return Err("branch leaves more than one construct".to_string()); - } - if frame.merge_dispatches { - let flow = self.flow_id_of(target); - return Ok(Action::Dispatch { - label: frame.merge_label, - flow, - }); - } - return Ok(Action::Goto(frame.merge_label)); + return Ok(Action { label, flow: None }); } } - Err("branch target is not reachable from the enclosing constructs".to_string()) + let depth = stack + .iter() + .rposition(|frame| frame.next_entries.contains(&target)) + .ok_or_else(|| "branch target is outside every enclosing construct".to_string())?; + let records_flow = stack[depth].dispatches || self.merge_flow.contains(&stack[depth].id); + let flow = records_flow.then(|| self.flow_id_of(target)); + let label = stack + .last() + .ok_or_else(|| "branch leaves a construct at the top level".to_string())? + .merge_label; + Ok(Action { label, flow }) } - /// How to enter `shape` at `target`, if `shape` starts there. - fn enter(&mut self, target: Word, shape: &Shape) -> Result, String> { + /// How to enter `shape` at `target`, which is one of its entries. + fn enter(&mut self, shape: &Shape, target: Word) -> Result { match shape { - Shape::Simple { label, .. } => Ok((*label == target).then_some(Action::Goto(*label))), - Shape::Loop { entries, .. } => { - if !entries.contains(&target) { - return Ok(None); - } - if entries.len() > 1 { - return Err("loop with several entries".to_string()); - } - Ok(Some(Action::Goto(self.start_of(shape)))) + Shape::Simple { .. } | Shape::Loop { .. } => { + let (label, _) = self.entry_label(shape, target)?; + Ok(Action { label, flow: None }) } - Shape::Multiple { id, handled, next } => { + Shape::Multiple { id, handled, .. } => { if handled.iter().any(|(label, _)| *label == target) { - if self.fused.contains(id) { - return Ok(Some(Action::Goto(target))); - } - let flow = self.flow_id_of(target); - return Ok(Some(Action::Dispatch { - label: self.start_of(shape), - flow, - })); - } - match next { - Some(next) => self.enter(target, next), - None => Ok(None), + let (label, needs_flow) = self.entry_label(shape, target)?; + let flow = needs_flow.then(|| self.flow_id_of(target)); + return Ok(Action { label, flow }); } + // The destination is past this dispatch: leave it through its merge, saying which + // continuation was meant when that merge reads the flow variable. + let label = self.merge_of(*id)?; + let flow = self.dispatches(*id).then(|| self.flow_id_of(target)); + Ok(Action { label, flow }) } } } + // ---------------------------------------------------------------- emission + fn emit(&mut self, shape: &Shape, stack: &mut Vec) -> Result<(), String> { match shape { Shape::Simple { label, next, .. } => self.emit_simple(*label, next.as_deref(), stack), Shape::Loop { + id, entries, inner, next, - .. - } => self.emit_loop(shape, entries, inner, next.as_deref(), stack), - Shape::Multiple { id, handled, next } => { - self.emit_multiple(*id, shape, handled, next.as_deref(), stack) - } + } => self.emit_loop(*id, entries, inner, next.as_deref(), stack), + Shape::Multiple { + id, handled, next, .. + } => self.emit_multiple(*id, handled, next.as_deref(), stack), } } @@ -404,6 +743,7 @@ impl Emitter<'_, '_> { let term = self .terms .get(&label) + .cloned() .ok_or_else(|| "missing terminator".to_string())?; let mut block = Block::new(); block.label = source.label.clone(); @@ -415,14 +755,11 @@ impl Emitter<'_, '_> { vec![Operand::IdRef(var)], )); } - block.instructions.extend( - source - .instructions - .iter() - .take(source.instructions.len().saturating_sub(1)) - .cloned(), - ); - self.emit_terminator(label, term.clone(), &mut block, next, stack)?; + let body = source.instructions.len().saturating_sub(1); + block + .instructions + .extend(source.instructions.iter().take(body).cloned()); + self.emit_terminator(label, term, &mut block, next, stack)?; self.out.push(block); if let Some(next) = next { self.emit(next, stack)?; @@ -430,7 +767,6 @@ impl Emitter<'_, '_> { Ok(()) } - /// Write the branch structure for `label`'s terminator, appending any per-edge helper blocks. fn emit_terminator( &mut self, label: Word, @@ -440,33 +776,45 @@ impl Emitter<'_, '_> { stack: &[Frame], ) -> Result<(), String> { match term { - Term::Return | Term::Unreachable | Term::ReturnValue(_) | Term::Kill(_) => { - let instruction = match term { - Term::Return => Instruction::new(Op::Return, None, None, vec![]), - Term::ReturnValue(value) => { - Instruction::new(Op::ReturnValue, None, None, vec![Operand::IdRef(value)]) - } - Term::Unreachable => Instruction::new(Op::Unreachable, None, None, vec![]), - Term::Kill(instruction) => instruction, - _ => unreachable!("matched above"), - }; + Term::Return => { + block + .instructions + .push(Instruction::new(Op::Return, None, None, vec![])); + Ok(()) + } + Term::ReturnValue(value) => { + block.instructions.push(Instruction::new( + Op::ReturnValue, + None, + None, + vec![Operand::IdRef(value)], + )); + Ok(()) + } + Term::Unreachable => { + block + .instructions + .push(Instruction::new(Op::Unreachable, None, None, vec![])); + Ok(()) + } + Term::Kill(instruction) => { block.instructions.push(instruction); Ok(()) } Term::Branch(target) => { let action = self.resolve(target, next, stack)?; - self.apply(label, target, action, block); + self.finish_single_edge(label, target, action, block); Ok(()) } Term::BranchCond(condition, on_true, on_false) => { if on_true == on_false { let action = self.resolve(on_true, next, stack)?; - self.apply(label, on_true, action, block); + self.finish_single_edge(label, on_true, action, block); return Ok(()); } let true_label = self.edge_label(label, on_true, next, stack)?; let false_label = self.edge_label(label, on_false, next, stack)?; - let merge = self.selection_merge(next); + let merge = self.selection_merge(next)?; block.instructions.push(Instruction::new( Op::SelectionMerge, None, @@ -476,6 +824,24 @@ impl Emitter<'_, '_> { Operand::SelectionControl(SelectionControl::NONE), ], )); + if self.needs_switch(next) { + // Something nested in one of these arms breaks out past this construct, and + // SPIR-V allows that only for a loop or a switch. Widen the condition to a + // selector so the two-way choice is a switch construct. + let selector = self.widen_condition(condition, block); + block.instructions.push(Instruction::new( + Op::Switch, + None, + None, + vec![ + Operand::IdRef(selector), + Operand::IdRef(false_label), + Operand::LiteralBit32(1), + Operand::IdRef(true_label), + ], + )); + return Ok(()); + } block.instructions.push(Instruction::new( Op::BranchConditional, None, @@ -500,7 +866,7 @@ impl Emitter<'_, '_> { }); operands.push(Operand::IdRef(case_label)); } - let merge = self.selection_merge(next); + let merge = self.selection_merge(next)?; block.instructions.push(Instruction::new( Op::SelectionMerge, None, @@ -518,18 +884,45 @@ impl Emitter<'_, '_> { } } - /// The declared merge for a divergent terminator: wherever the shape that follows begins. A - /// terminator whose arms all leave the enclosing construct has no continuation, so it declares - /// a merge block nothing reaches. - fn selection_merge(&mut self, next: Option<&Shape>) -> Word { + /// Whether the construct a divergent terminator heads has to be written as a switch. + fn needs_switch(&self, next: Option<&Shape>) -> bool { + matches!(next, Some(Shape::Multiple { id, .. }) + if self.facts.get(id).is_some_and(|facts| facts.needs_switch)) + } + + /// A `0`/`1` selector for a boolean condition, so a two-way choice can head a switch construct. + fn widen_condition(&mut self, condition: Word, block: &mut Block) -> Word { + let one = self.tc.int_const(self.flow_ty, 1); + let zero = self.tc.int_const(self.flow_ty, 0); + let selector = self.tc.fresh(); + let selection = Instruction::new( + Op::Select, + Some(self.flow_ty), + Some(selector), + vec![ + Operand::IdRef(condition), + Operand::IdRef(one), + Operand::IdRef(zero), + ], + ); + // OpSelectionMerge must stay immediately before the branch, so the widening goes in front. + let position = block.instructions.len().saturating_sub(1); + block.instructions.insert(position, selection); + selector + } + + /// The declared merge for a divergent terminator: where the shape that follows converges. A + /// terminator whose arms all leave the enclosing construct declares a merge nothing reaches. + fn selection_merge(&mut self, next: Option<&Shape>) -> Result { match next { - Some(next) => self.start_of(next), - None => self.fresh_unreachable(), + Some(Shape::Multiple { id, .. }) => self.merge_of(*id), + Some(shape) => self.head_of(shape), + None => Ok(self.fresh_unreachable()), } } - /// The label a single outgoing edge branches to, creating a helper block when that edge has to - /// store phi values or a flow id before it can branch. + /// The label one outgoing edge branches to, creating a helper block when the edge has to store + /// phi values or a flow destination before branching. fn edge_label( &mut self, from: Word, @@ -543,23 +936,46 @@ impl Emitter<'_, '_> { .get(&(from, target)) .cloned() .unwrap_or_default(); - let flow = match action { - Action::Goto(label) if stores.is_empty() => return Ok(label), - Action::Goto(_) => None, - Action::Dispatch { flow, .. } => Some(flow), - }; - let destination = match action { - Action::Goto(label) | Action::Dispatch { label, .. } => label, - }; + if stores.is_empty() && action.flow.is_none() { + return Ok(action.label); + } let helper = self.tc.fresh(); let mut block = Block::new(); block.label = Some(Instruction::new(Op::Label, None, Some(helper), vec![])); + self.write_edge_stores(&stores, action.flow, &mut block); + block.instructions.push(Instruction::new( + Op::Branch, + None, + None, + vec![Operand::IdRef(action.label)], + )); + self.out.push(block); + Ok(helper) + } + + /// Finish a block whose terminator has one outgoing edge: its stores go inline. + fn finish_single_edge(&mut self, from: Word, target: Word, action: Action, block: &mut Block) { + let stores = self + .phi_stores + .get(&(from, target)) + .cloned() + .unwrap_or_default(); + self.write_edge_stores(&stores, action.flow, block); + block.instructions.push(Instruction::new( + Op::Branch, + None, + None, + vec![Operand::IdRef(action.label)], + )); + } + + fn write_edge_stores(&mut self, stores: &[(Word, Word)], flow: Option, block: &mut Block) { for (var, value) in stores { block.instructions.push(Instruction::new( Op::Store, None, None, - vec![Operand::IdRef(var), Operand::IdRef(value)], + vec![Operand::IdRef(*var), Operand::IdRef(*value)], )); } if let Some(flow) = flow { @@ -572,71 +988,24 @@ impl Emitter<'_, '_> { vec![Operand::IdRef(variable), Operand::IdRef(constant)], )); } - block.instructions.push(Instruction::new( - Op::Branch, - None, - None, - vec![Operand::IdRef(destination)], - )); - self.out.push(block); - Ok(helper) - } - - /// Finish a block whose terminator has one outgoing edge: the stores can go inline. - fn apply(&mut self, from: Word, target: Word, action: Action, block: &mut Block) { - for (var, value) in self - .phi_stores - .get(&(from, target)) - .cloned() - .unwrap_or_default() - { - block.instructions.push(Instruction::new( - Op::Store, - None, - None, - vec![Operand::IdRef(var), Operand::IdRef(value)], - )); - } - let destination = match action { - Action::Goto(label) => label, - Action::Dispatch { label, flow } => { - let variable = self.flow_variable(); - let constant = self.tc.int_const(self.flow_ty, flow); - block.instructions.push(Instruction::new( - Op::Store, - None, - None, - vec![Operand::IdRef(variable), Operand::IdRef(constant)], - )); - label - } - }; - block.instructions.push(Instruction::new( - Op::Branch, - None, - None, - vec![Operand::IdRef(destination)], - )); } fn emit_loop( &mut self, - shape: &Shape, + id: usize, entries: &BTreeSet, inner: &Shape, next: Option<&Shape>, stack: &mut Vec, ) -> Result<(), String> { - if entries.len() != 1 { - return Err("loop with several entries".to_string()); - } - let header = self.start_of(shape); + let header = self + .head + .get(&id) + .copied() + .ok_or_else(|| "loop without a header".to_string())?; let continue_label = self.tc.fresh(); - let merge_label = match next { - Some(next) => self.start_of(next), - None => self.fresh_unreachable(), - }; - let body_start = self.start_of(inner); + let merge_label = self.merge_of(id)?; + let body_start = self.head_of(inner)?; let mut head = Block::new(); head.label = Some(Instruction::new(Op::Label, None, Some(header), vec![])); head.instructions.push(Instruction::new( @@ -658,11 +1027,12 @@ impl Emitter<'_, '_> { self.out.push(head); stack.push(Frame { + id, loop_entries: entries.clone(), continue_label: Some(continue_label), merge_label, next_entries: next.map(Shape::entry_labels).unwrap_or_default(), - merge_dispatches: next.is_some_and(|next| self.needs_dispatch(next)), + dispatches: self.dispatches(id), }); let result = self.emit(inner, stack); stack.pop(); @@ -683,71 +1053,30 @@ impl Emitter<'_, '_> { )); self.out.push(latch); - if let Some(next) = next { - self.emit(next, stack)?; - } - Ok(()) - } - - fn needs_dispatch(&self, shape: &Shape) -> bool { - matches!(shape, Shape::Multiple { id, handled, .. } - if !handled.is_empty() && !self.fused.contains(id)) + self.emit_construct_tail(id, next, stack) } + /// A dispatch occupies no block of its own: it is entered either by the terminator it fused + /// into or by the enclosing construct's merge dispatch, both of which branch straight at the + /// arm they selected. Emitting it is therefore emitting the arms, then the continuation. fn emit_multiple( &mut self, id: usize, - shape: &Shape, handled: &[(Word, Shape)], next: Option<&Shape>, stack: &mut Vec, ) -> Result<(), String> { - let merge_label = match next { - Some(next) => self.start_of(next), - None => self.fresh_unreachable(), - }; - if !self.fused.contains(&id) && !handled.is_empty() { - // Several terminators reach this dispatch, so the flow variable says which arm was - // meant. The dispatch block IS this shape's start, which is also the enclosing - // construct's merge, so control arrives here by an ordinary structured exit. - let dispatch = self.start_of(shape); - let variable = self.flow_variable(); - let loaded = self.tc.fresh(); - let mut block = Block::new(); - block.label = Some(Instruction::new(Op::Label, None, Some(dispatch), vec![])); - block.instructions.push(Instruction::new( - Op::Load, - Some(self.flow_ty), - Some(loaded), - vec![Operand::IdRef(variable)], - )); - let mut operands = vec![Operand::IdRef(loaded), Operand::IdRef(merge_label)]; - for (entry, _) in handled { - let flow = self.flow_id_of(*entry); - operands.push(Operand::LiteralBit32(flow as u32)); - operands.push(Operand::IdRef(*entry)); - } - block.instructions.push(Instruction::new( - Op::SelectionMerge, - None, - None, - vec![ - Operand::IdRef(merge_label), - Operand::SelectionControl(SelectionControl::NONE), - ], - )); - block - .instructions - .push(Instruction::new(Op::Switch, None, None, operands)); - self.out.push(block); + let merge_label = self.merge_of(id)?; + if !self.fused.contains(&id) { + self.emit_dispatch_header(id, handled, merge_label)?; } - stack.push(Frame { + id, loop_entries: BTreeSet::new(), continue_label: None, merge_label, next_entries: next.map(Shape::entry_labels).unwrap_or_default(), - merge_dispatches: next.is_some_and(|next| self.needs_dispatch(next)), + dispatches: self.dispatches(id), }); let mut result = Ok(()); for (_, arm) in handled { @@ -759,9 +1088,168 @@ impl Emitter<'_, '_> { stack.pop(); result?; - if let Some(next) = next { - self.emit(next, stack)?; + self.emit_construct_tail(id, next, stack) + } + + /// The header of a dispatch entered from an enclosing construct rather than fused into one + /// terminator. Making it a real `OpSwitch` header is what gives the dispatch a merge block that + /// constructs nested inside its arms are allowed to break to. + fn emit_dispatch_header( + &mut self, + id: usize, + handled: &[(Word, Shape)], + merge_label: Word, + ) -> Result<(), String> { + let header = self + .head + .get(&id) + .copied() + .ok_or_else(|| "dispatch without a header".to_string())?; + let variable = self.flow_variable(); + let loaded = self.tc.fresh(); + let mut block = Block::new(); + block.label = Some(Instruction::new(Op::Label, None, Some(header), vec![])); + block.instructions.push(Instruction::new( + Op::Load, + Some(self.flow_ty), + Some(loaded), + vec![Operand::IdRef(variable)], + )); + // The default is this construct's merge: a destination past the arms leaves again there, + // where the dispatch that routes it on already has a case for it. + let mut operands = vec![Operand::IdRef(loaded), Operand::IdRef(merge_label)]; + for (arm, shape) in handled { + let flow = self.flow_id_of(*arm); + let head = self.head_of(shape)?; + operands.push(Operand::LiteralBit32(flow as u32)); + operands.push(Operand::IdRef(head)); } + block.instructions.push(Instruction::new( + Op::SelectionMerge, + None, + None, + vec![ + Operand::IdRef(merge_label), + Operand::SelectionControl(SelectionControl::NONE), + ], + )); + block + .instructions + .push(Instruction::new(Op::Switch, None, None, operands)); + self.out.push(block); + Ok(()) + } + + /// Write whatever follows a construct. + /// + /// Without a dispatch that is just the continuation, which already starts at the construct's + /// merge. With one, the merge reads the flow variable and either enters the continuation at the + /// destination it names or forwards outward through its own merge block — the one block that is + /// directly inside the next construct out, and so may branch at that construct's merge. + fn emit_construct_tail( + &mut self, + id: usize, + next: Option<&Shape>, + stack: &mut Vec, + ) -> Result<(), String> { + if !self.dispatches(id) { + return match next { + Some(next) => self.emit(next, stack), + None => Ok(()), + }; + } + let dispatch = self.merge_of(id)?; + let destinations = self + .facts + .get(&id) + .map(|facts| facts.destinations.iter().copied().collect::>()) + .unwrap_or_default(); + let Some(next) = next else { + // Nothing follows this construct, so every edge arriving at its merge is a staged one + // still on its way out. Forward without reading the variable: there is no destination + // here to compare against. + let mut block = Block::new(); + block.label = Some(Instruction::new(Op::Label, None, Some(dispatch), vec![])); + match stack.last().map(|frame| frame.merge_label) { + Some(outer) => block.instructions.push(Instruction::new( + Op::Branch, + None, + None, + vec![Operand::IdRef(outer)], + )), + None => { + block + .instructions + .push(Instruction::new(Op::Unreachable, None, None, vec![])) + } + } + self.out.push(block); + return Ok(()); + }; + let after = self.tc.fresh(); + let mut cases: Vec<(u64, Word)> = Vec::with_capacity(destinations.len()); + for destination in destinations { + let (label, _) = self.entry_label(next, destination)?; + cases.push((self.flow_id_of(destination), label)); + } + let variable = self.flow_variable(); + let loaded = self.tc.fresh(); + let mut block = Block::new(); + block.label = Some(Instruction::new(Op::Label, None, Some(dispatch), vec![])); + block.instructions.push(Instruction::new( + Op::Load, + Some(self.flow_ty), + Some(loaded), + vec![Operand::IdRef(variable)], + )); + // The default forwards: a destination this construct does not own belongs further out, and + // `after` is where the dispatch converges, directly inside the next construct. + let mut operands = vec![Operand::IdRef(loaded), Operand::IdRef(after)]; + for (flow, label) in &cases { + operands.push(Operand::LiteralBit32(*flow as u32)); + operands.push(Operand::IdRef(*label)); + } + block.instructions.push(Instruction::new( + Op::SelectionMerge, + None, + None, + vec![ + Operand::IdRef(after), + Operand::SelectionControl(SelectionControl::NONE), + ], + )); + block + .instructions + .push(Instruction::new(Op::Switch, None, None, operands)); + self.out.push(block); + + // The continuation is written inside the dispatch's selection, so anything in it that + // leaves this nesting level converges at `after` instead of branching past it. + let restore = stack.last().map(|frame| frame.merge_label); + if let Some(frame) = stack.last_mut() { + frame.merge_label = after; + } + let result = self.emit(next, stack); + if let (Some(frame), Some(restore)) = (stack.last_mut(), restore) { + frame.merge_label = restore; + } + result?; + + let mut tail = Block::new(); + tail.label = Some(Instruction::new(Op::Label, None, Some(after), vec![])); + match restore { + Some(outer) => tail.instructions.push(Instruction::new( + Op::Branch, + None, + None, + vec![Operand::IdRef(outer)], + )), + // Nothing encloses this construct, so no staged edge can be pending here. + None => tail + .instructions + .push(Instruction::new(Op::Unreachable, None, None, vec![])), + } + self.out.push(tail); Ok(()) } } diff --git a/src/native/reloop_nest/mod.rs b/src/native/reloop_nest/mod.rs index addb58389..5bc05cf34 100644 --- a/src/native/reloop_nest/mod.rs +++ b/src/native/reloop_nest/mod.rs @@ -375,6 +375,58 @@ mod tests { assert!(asm.contains("OpIAdd"), "{asm}"); } + /// `while (c) { if (d) { p(); if (e) break; } q(); }` — the break leaves a selection AND the + /// loop on one edge, which SPIR-V cannot express as a single branch. + const NESTED_BREAK: &str = r#" + OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" + OpExecutionMode %main LocalSize 1 1 1 + %void = OpTypeVoid + %uint = OpTypeInt 32 0 + %bool = OpTypeBool + %uint_0 = OpConstant %uint 0 + %uint_1 = OpConstant %uint 1 + %uint_3 = OpConstant %uint 3 + %uint_8 = OpConstant %uint 8 + %fnvoid = OpTypeFunction %void + %main = OpFunction %void None %fnvoid + %entry = OpLabel + OpBranch %header + %header = OpLabel + %i = OpPhi %uint %uint_0 %entry %next %latch + %c = OpULessThan %bool %i %uint_8 + OpBranchConditional %c %body %exit + %body = OpLabel + %d = OpIEqual %bool %i %uint_1 + OpBranchConditional %d %then %q + %then = OpLabel + %p = OpIMul %uint %i %uint_3 + %e = OpIEqual %bool %p %uint_3 + OpBranchConditional %e %exit %q + %q = OpLabel + OpBranch %latch + %latch = OpLabel + %next = OpIAdd %uint %i %uint_1 + OpBranch %header + %exit = OpLabel + OpReturn + OpFunctionEnd +"#; + + #[test] + fn a_break_leaving_two_constructs_is_staged_and_validates() { + let Some(spv) = assemble(NESTED_BREAK) else { + return; + }; + let nested = nested_bytes(&spv).expect("reducible control flow is nested"); + assert!(validates(&nested)); + let asm = disassemble(&nested); + assert!(asm.contains("OpLoopMerge"), "{asm}"); + // The loop is a real loop, not a case of a whole-function dispatch. + assert_eq!(asm.matches("OpLoopMerge").count(), 1, "{asm}"); + } + #[test] fn irreducible_control_flow_is_declined() { let irreducible = r#" diff --git a/src/native/reloop_nest/shape.rs b/src/native/reloop_nest/shape.rs index bd54e2fe6..5f6de1128 100644 --- a/src/native/reloop_nest/shape.rs +++ b/src/native/reloop_nest/shape.rs @@ -189,6 +189,9 @@ pub(super) enum Shape { /// arms share follows in `next`. Multiple { id: usize, + /// The labels control can arrive at, which is not the arm list: an entry whose region is + /// shared with another entry owns no arm and is reached through `next`. + entries: BTreeSet