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.
This commit is contained in:
Anees Iqbal committed 2026-08-31 11:34:38 +03:00
1 parent 465c76d41e
commit 0ac159bd6f
3 files changed
+848 -310

No files matched your search

File diff suppressed because it is too large. Load diff
+52
View File
@@ -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#"
+17 -19
View File
@@ -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<Label>,
handled: Vec<(Label, Shape)>,
next: Option<Box<Shape>>,
},
@@ -201,22 +204,13 @@ impl Shape {
}
}
/// The labels this shape can be entered at. A branch whose target is in this set is a branch
/// *into* the shape rather than past it.
/// Exactly the labels control can arrive at from outside this shape. A branch whose target is
/// in this set enters the shape; anything else passes it by, which is what tells the emitter a
/// branch has to leave more than one construct.
pub(super) fn entry_labels(&self) -> BTreeSet<Label> {
match self {
Shape::Simple { label, .. } => BTreeSet::from([*label]),
Shape::Loop { entries, .. } => entries.clone(),
Shape::Multiple { handled, next, .. } => {
let mut labels = handled
.iter()
.map(|(label, _)| *label)
.collect::<BTreeSet<_>>();
if let Some(next) = next {
labels.extend(next.entry_labels());
}
labels
}
Shape::Loop { entries, .. } | Shape::Multiple { entries, .. } => entries.clone(),
}
}
}
@@ -331,15 +325,18 @@ fn make_loop(
cut.remove(&edge);
}
let next = calculate_region(graph, blocks, next_entries, cut, counter);
// A loop body always covers at least its entries, so the recursion cannot decline; the empty
// dispatch is an unconstructible placeholder the emitter rejects rather than a real shape.
let inner = body.unwrap_or_else(|| Shape::Multiple {
id: fresh(counter),
entries: entries.clone(),
handled: Vec::new(),
next: None,
});
Shape::Loop {
id,
entries,
// A loop body always covers at least its entries, so the recursion cannot decline.
inner: Box::new(body.unwrap_or(Shape::Multiple {
id: fresh(counter),
handled: Vec::new(),
next: None,
})),
inner: Box::new(inner),
next: next.map(Box::new),
}
}
@@ -386,6 +383,7 @@ fn make_multiple(
let next = calculate_region(graph, blocks, next_entries, cut, counter);
Shape::Multiple {
id,
entries,
handled,
next: next.map(Box::new),
}