Files
metal2vulkan/src/native/tests/mod.rs
T
Anees Iqbal c43bb11612 Record the structurizer's selection splits too, and count the analyses so neither comes back
The selection structurizer re-derived dominance and rebuilt the source CFG after every private
merge it spliced in, the same defect fixed one commit ago in the merge-ownership pass. Counted on
the slowest source in the local corpus -- a 44-block kernel that took 4.2 seconds -- translation
built 19,384 source CFGs, and 9,522 of them, 55% of the total block-visits, came from that one
statement. It is now 2.7 seconds, and it is the slowest source in the corpus by wall clock.

`unique_selection_merges_with_loop_exit_and_forced_inner` splices a pass-through in front of a
shared natural merge, once per header that claims it, and the `!construct_tree_owned` arms then
re-derived so the new block would participate in the next header's ownership question. Recording
the split answers that exactly, for the reasons `Dominators::record_pass_through` sets out: a
pass-through elides out of every path through it, so the blocks that were already there keep their
dominators, and the new block's follow from its predecessors. The natural loops were already known
to be unchanged -- an acyclic pass-through in front of an existing block adds no back edge -- which
is why the old code called `analyze_reusing_natural_loops` rather than `analyze`.

The last commit's `PassThroughDominance` is folded into `Dominators` itself. The structurizer's
`cur_forest` has to stay a `LoopForest` (the synthesis functions take one), so the recording has to
be reachable from there; putting it on the dominator relation gives it to both callers with no
signature churn, and `LoopForest::record_pass_through` forwards. The contract that a pass-through is
never itself a split target is now a `debug_assert!` that costs nothing until something records.

`header_owned_merge_predecessors` replaces two identical copies of the rule for which predecessors a
selection header owns. It has a third caller now -- recording a split means naming the edges it
carried -- and three copies of that filter would be three things to keep in step.

Two regression guards, because the two ways to be quadratic need different instruments:

* `src/native/tests/bounded_work.rs` counts source CFG constructions for a kernel whose loop exit is
  claimed by six selections. 871 as it stands; 2209 with the re-derivation put back; the bound is
  1400. The count is exact and machine-independent -- six sizes reproduce to the block over repeated
  runs -- where the wall time this defect actually costs is neither. The counter is `#[cfg(test)]`,
  thread-local, and absent from a release library.
* `tests/bounded_growth.rs`'s total-allocation bound, added last commit, is what covers the
  merge-ownership pass; this kernel does not reach that pass, and its peak-memory bound sees
  neither. Both files now say which defect each number catches.

Verified byte-identical over 2880 local corpus sources, and over the generated irreducible chain at
1502, 3002 and 6002 blocks. A fresh timing sweep over the same 2880: 0 over the 20-second ceiling,
slowest 2.74s. Full gate green -- fmt, clippy `-D warnings`, rustdoc `-D warnings`,
`cargo test --release -p metal2vulkan`, `cargo test -p metal2vulkan-validation`, and the debug build
so the new `debug_assert!` and the counter both run.

Not claimed fixed: 871 whole-function analyses for a seventeen-block kernel is still far more than
that kernel is worth, and the retry ladder, not any one pass, is where the rest of them come from.
2026-08-31 19:12:03 +03:00

217 lines
7.3 KiB
Rust

// Shared test-helper infrastructure. The ~422 `#[test]` functions themselves live in the semantic
// submodules declared below (buffers/control_flow/textures/… — the T1 split); this file keeps only the
// imports the helpers need. Each submodule re-imports the emitter/cfg/ir surface it exercises and globs
// `use super::*` to reach these helpers.
use crate::spirv_module::Operand;
use crate::spirv_module::{load_bytes, Module};
use spirv::{Decoration, Op, StorageClass, Word};
use std::collections::{HashMap, HashSet};
mod bounded_work;
mod buffers;
mod control_flow;
mod interface;
mod intrinsics;
mod misc;
mod textures;
mod threadgroup;
mod types;
fn asm_has_line(asm: &str, needle: &str) -> bool {
asm.lines().any(|line| line.trim() == needle)
}
/// Isolate non-dispatch lowering tests from the safe dynamic-grid prologue. Tests using this helper
/// explicitly model a caller that dispatches complete workgroups.
fn whole_workgroup_options() -> crate::passes::TransformOptions {
crate::passes::TransformOptions {
kernel_dispatch: Some(crate::reflect::KernelDispatch::Workgroups),
..crate::passes::TransformOptions::default()
}
}
fn assert_no_pointer_bitcasts(spv: &[u8]) {
let module = load_bytes(spv).expect("load spv");
let pointer_types = module
.types_global_values
.iter()
.filter_map(|inst| {
(inst.class.opcode == Op::TypePointer)
.then_some(inst.result_id)
.flatten()
})
.collect::<HashSet<_>>();
let pointer_bitcast = module.all_inst_iter().find(|inst| {
inst.class.opcode == Op::Bitcast
&& inst
.result_type
.is_some_and(|ty| pointer_types.contains(&ty))
});
assert!(pointer_bitcast.is_none(), "{pointer_bitcast:?}");
}
/// The disassembly id of the 32-bit unsigned int type (`OpTypeInt 32 0`). Ids are canonicalized to a
/// deterministic numbering, so tests resolve type ids by structure rather than hardcoding numbers.
fn uint32_type_id(asm: &str) -> String {
asm.lines()
.find(|line| line.trim_end().ends_with("OpTypeInt 32 0"))
.and_then(|line| line.split_whitespace().next())
.unwrap_or("%uint")
.to_string()
}
fn interface_variable_at_location(
module: &Module,
storage: StorageClass,
location: u32,
) -> Option<Word> {
module.annotations.iter().find_map(|inst| {
if inst.class.opcode != Op::Decorate {
return None;
}
let [
Operand::IdRef(id),
Operand::Decoration(Decoration::Location),
Operand::LiteralBit32(loc),
] = inst.operands.as_slice()
else {
return None;
};
if *loc != location || variable_storage_class(module, *id) != Some(storage) {
return None;
}
Some(*id)
})
}
fn variable_storage_class(module: &Module, var: Word) -> Option<StorageClass> {
module.types_global_values.iter().find_map(|inst| {
if inst.class.opcode == Op::Variable && inst.result_id == Some(var) {
if let Some(Operand::StorageClass(storage)) = inst.operands.first() {
return Some(*storage);
}
}
None
})
}
fn pointer_type_storage_class(module: &Module, ptr_ty: Word) -> Option<StorageClass> {
module.types_global_values.iter().find_map(|inst| {
if inst.class.opcode == Op::TypePointer && inst.result_id == Some(ptr_ty) {
if let Some(Operand::StorageClass(storage)) = inst.operands.first() {
return Some(*storage);
}
}
None
})
}
fn variable_pointee_type(module: &Module, var: Word) -> Option<Word> {
let ptr_ty = module.types_global_values.iter().find_map(|inst| {
if inst.class.opcode == Op::Variable && inst.result_id == Some(var) {
inst.result_type
} else {
None
}
})?;
module.types_global_values.iter().find_map(|inst| {
if inst.class.opcode == Op::TypePointer && inst.result_id == Some(ptr_ty) {
if let Some(Operand::IdRef(pointee)) = inst.operands.get(1) {
return Some(*pointee);
}
}
None
})
}
fn assert_phi_operand_types_match(module: &Module, asm: &str) {
let result_types = module
.all_inst_iter()
.filter_map(|inst| Some((inst.result_id?, inst.result_type?)))
.collect::<HashMap<_, _>>();
for inst in module.all_inst_iter() {
if inst.class.opcode != Op::Phi {
continue;
}
let Some(result_type) = inst.result_type else {
continue;
};
for incoming in inst.operands.chunks(2) {
let [Operand::IdRef(value), Operand::IdRef(_label)] = incoming else {
continue;
};
assert_eq!(
result_types.get(value),
Some(&result_type),
"phi {:?} incoming value {value} has mismatched type\n{asm}",
inst.result_id
);
}
}
}
fn is_unsigned_int_vector(module: &Module, ty: Word, bits: u32, lanes: u32) -> bool {
let Some(elem) = module.types_global_values.iter().find_map(|inst| {
if inst.class.opcode == Op::TypeVector
&& inst.result_id == Some(ty)
&& inst.operands.get(1) == Some(&Operand::LiteralBit32(lanes))
{
if let Some(Operand::IdRef(elem)) = inst.operands.first() {
return Some(*elem);
}
}
None
}) else {
return false;
};
module.types_global_values.iter().any(|inst| {
inst.class.opcode == Op::TypeInt
&& inst.result_id == Some(elem)
&& inst.operands.first() == Some(&Operand::LiteralBit32(bits))
&& inst.operands.get(1) == Some(&Operand::LiteralBit32(0))
})
}
fn is_float_vector(module: &Module, ty: Word, lanes: u32) -> bool {
let Some(elem) = module.types_global_values.iter().find_map(|inst| {
if inst.class.opcode == Op::TypeVector
&& inst.result_id == Some(ty)
&& inst.operands.get(1) == Some(&Operand::LiteralBit32(lanes))
{
if let Some(Operand::IdRef(elem)) = inst.operands.first() {
return Some(*elem);
}
}
None
}) else {
return false;
};
module.types_global_values.iter().any(|inst| {
inst.class.opcode == Op::TypeFloat
&& inst.result_id == Some(elem)
&& inst.operands.first() == Some(&Operand::LiteralBit32(32))
})
}
fn is_signed_i32_vector(module: &Module, ty: Word, lanes: u32) -> bool {
let Some(elem) = module.types_global_values.iter().find_map(|inst| {
if inst.class.opcode == Op::TypeVector
&& inst.result_id == Some(ty)
&& inst.operands.get(1) == Some(&Operand::LiteralBit32(lanes))
{
if let Some(Operand::IdRef(elem)) = inst.operands.first() {
return Some(*elem);
}
}
None
}) else {
return false;
};
module.types_global_values.iter().any(|inst| {
inst.class.opcode == Op::TypeInt
&& inst.result_id == Some(elem)
&& inst.operands.first() == Some(&Operand::LiteralBit32(32))
&& inst.operands.get(1) == Some(&Operand::LiteralBit32(1))
})
}