diff --git a/src/lib.rs b/src/lib.rs index 5a93598b2..13d69f3e5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -960,6 +960,13 @@ fn finish_module( native::construct_cfg_functions_module(&mut out, &cfg_construction_functions) .map_err(FinishFailure::cfg)?; native::construct_physical_atomic_pointer_lvalues_module(&mut out); + // Every instruction-deleting step of this boundary has run. Dead-value elimination, constant-CFG + // pruning, and CFG construction all delete uses after `transform` established global liveness, + // so a variable can outlive its last use here; re-establish liveness before the module is sealed. + // An interface entry naming a descriptor binding no instruction touches is a demand on every + // consumer that builds its layout from the interface. This runs ahead of the constant sweep + // below so the initializers it strands are collected in the same step. + passes::drop_unreferenced_global_variables(&mut out); // CFG construction rematerializes values used by the selected representation. Discard any // null/undef constants that become dead in that final graph; under PhysicalStorageBuffer64 an // otherwise unreferenced logical-pointer null is still structurally invalid SPIR-V. diff --git a/src/passes/mod.rs b/src/passes/mod.rs index d31a68f20..ceafee198 100644 --- a/src/passes/mod.rs +++ b/src/passes/mod.rs @@ -1546,6 +1546,7 @@ mod finalize; #[cfg(test)] mod lowering_regression_tests; mod module_cleanup; +pub(crate) use module_cleanup::drop_unreferenced_global_variables; mod prune; mod resources; mod spirv_cfg; @@ -2661,6 +2662,10 @@ pub(crate) fn transform_with_options_and_sidecar( // sealing synthesized before global liveness runs. decorate_ptr_access_chain_base_strides(&mut ctx); ctx.module.types_global_values.append(&mut ctx.new_globals); + // The closures above are the last of this boundary's instruction changes, and any of them can + // delete a variable's last use. Re-establish global liveness against the finished bodies before + // the collection that would otherwise root a stranded variable at its own interface entry. + module_cleanup::drop_unreferenced_global_variables(&mut ctx.module); module_cleanup::gc_dead_globals(&mut ctx); debug_phase!("complete"); diff --git a/src/passes/module_cleanup.rs b/src/passes/module_cleanup.rs index 3d479a30d..928ec821d 100644 --- a/src/passes/module_cleanup.rs +++ b/src/passes/module_cleanup.rs @@ -82,6 +82,68 @@ pub(super) fn drop_dead_unreferenced_variables( }); } +/// Whether a non-semantic record (`OpName`, `OpDecorate`, `OpMemberName`, `OpMemberDecorate`) is +/// about one of `removed`. Every one of them names its target first. +fn targets_any(instruction: &Instruction, removed: &HashSet) -> bool { + matches!(instruction.operands.first(), Some(Operand::IdRef(id)) if removed.contains(id)) +} + +/// Drop every global `OpVariable` no instruction references, together with its entry-point interface +/// entry, its decorations, and its debug names. Returns whether anything was removed. +/// +/// `finalize` applies this rule once, against the bodies as they stand when it builds the entry +/// point. Instruction-deleting work runs after it at two boundaries — the pointer and access-chain +/// closures at the end of `transform`, and dead-value elimination plus constant-CFG pruning in +/// `finish_module` — and when one of those deletes a variable's last use, nothing downstream can +/// remove the variable: `gc_dead_globals` roots liveness AT the entry-point interface, so the +/// interface entry keeps the variable alive and the variable justifies the interface entry. The +/// module then ships an `OpVariable` with a `DescriptorSet`/`Binding` no instruction touches, and a +/// consumer building a descriptor-set layout from the interface has to satisfy a binding the shader +/// never reads. +/// +/// Re-applying the rule after the last instruction-deleting step breaks that cycle. It can only +/// shrink the interface — an id kept here is one an instruction still names — so SPIR-V 1.4's +/// requirement that the interface list every global the entry point references is preserved. +pub(crate) fn drop_unreferenced_global_variables(module: &mut Module) -> bool { + /// `OpEntryPoint` operands: execution model, entry function id, name, then the interface ids. + const INTERFACE_START: usize = 3; + + let referenced = function_referenced_ids(module); + let removed = module + .types_global_values + .iter() + .filter(|instruction| instruction.class.opcode == Op::Variable) + .filter_map(|instruction| instruction.result_id) + .filter(|id| !referenced.contains(id)) + .collect::>(); + if removed.is_empty() { + return false; + } + for entry_point in &mut module.entry_points { + entry_point.operands = std::mem::take(&mut entry_point.operands) + .into_iter() + .enumerate() + .filter(|(index, operand)| match operand { + Operand::IdRef(id) if *index >= INTERFACE_START => !removed.contains(id), + _ => true, + }) + .map(|(_, operand)| operand) + .collect(); + } + module.types_global_values.retain(|instruction| { + instruction + .result_id + .is_none_or(|id| !removed.contains(&id)) + }); + module + .annotations + .retain(|instruction| !targets_any(instruction, &removed)); + module + .debug_names + .retain(|instruction| !targets_any(instruction, &removed)); + true +} + /// Remove OpName/OpDecorate/OpMemberDecorate whose target id is not defined anywhere. pub(super) fn drop_dangling_debug(ctx: &mut Ctx) { let defined = defined_ids(&ctx.module); @@ -621,6 +683,142 @@ mod tests { use crate::spirv_module::Module; use crate::spirv_module::ModuleHeader; + /// A module whose entry point lists two descriptor variables while only one is still loaded. + /// The second is what a pipeline boundary strands when a later rewrite deletes its last use. + fn module_with_one_stranded_descriptor() -> Module { + use crate::spirv_module::{Block, Function}; + let (uint, pointer, live, stranded, entry, loaded) = (1, 2, 3, 4, 5, 6); + let mut module = Module::new(); + module.header = Some(ModuleHeader::new(7)); + module.types_global_values = vec![ + Instruction::new( + Op::TypeInt, + None, + Some(uint), + vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)], + ), + Instruction::new( + Op::TypePointer, + None, + Some(pointer), + vec![ + Operand::StorageClass(StorageClass::StorageBuffer), + Operand::IdRef(uint), + ], + ), + Instruction::new( + Op::Variable, + Some(pointer), + Some(live), + vec![Operand::StorageClass(StorageClass::StorageBuffer)], + ), + Instruction::new( + Op::Variable, + Some(pointer), + Some(stranded), + vec![Operand::StorageClass(StorageClass::StorageBuffer)], + ), + ]; + for (variable, binding) in [(live, 0), (stranded, 1)] { + module.annotations.push(Instruction::new( + Op::Decorate, + None, + None, + vec![ + Operand::IdRef(variable), + Operand::Decoration(spirv::Decoration::Binding), + Operand::LiteralBit32(binding), + ], + )); + module.debug_names.push(Instruction::new( + Op::Name, + None, + None, + vec![ + Operand::IdRef(variable), + Operand::LiteralString(format!("buffer{binding}")), + ], + )); + } + module.entry_points.push(Instruction::new( + Op::EntryPoint, + None, + None, + vec![ + Operand::ExecutionModel(spirv::ExecutionModel::GLCompute), + Operand::IdRef(entry), + Operand::LiteralString("main".to_string()), + Operand::IdRef(live), + Operand::IdRef(stranded), + ], + )); + let mut function = Function::new(); + let mut block = Block::new(); + block.instructions.push(Instruction::new( + Op::Load, + Some(uint), + Some(loaded), + vec![Operand::IdRef(live)], + )); + function.blocks.push(block); + module.functions.push(function); + module + } + + /// The ids `module_with_one_stranded_descriptor` uses, in the order it names them. + const LIVE_VARIABLE: Word = 3; + const STRANDED_VARIABLE: Word = 4; + + fn variable_ids(module: &Module) -> HashSet { + module + .types_global_values + .iter() + .filter(|instruction| instruction.class.opcode == Op::Variable) + .filter_map(|instruction| instruction.result_id) + .collect() + } + + fn ids_named_by(records: &[Instruction]) -> HashSet { + records + .iter() + .filter_map(|instruction| match instruction.operands.first() { + Some(Operand::IdRef(id)) => Some(*id), + _ => None, + }) + .collect() + } + + #[test] + fn a_variable_no_instruction_references_leaves_with_its_interface_entry_and_records() { + let mut module = module_with_one_stranded_descriptor(); + + assert!(drop_unreferenced_global_variables(&mut module)); + + assert_eq!(variable_ids(&module), HashSet::from([LIVE_VARIABLE])); + let interface = module.entry_points[0].operands[3..] + .iter() + .filter_map(|operand| match operand { + Operand::IdRef(id) => Some(*id), + _ => None, + }) + .collect::>(); + assert_eq!(interface, HashSet::from([LIVE_VARIABLE])); + assert!(!ids_named_by(&module.annotations).contains(&STRANDED_VARIABLE)); + assert!(!ids_named_by(&module.debug_names).contains(&STRANDED_VARIABLE)); + // The surviving descriptor keeps everything that describes it. + assert!(ids_named_by(&module.annotations).contains(&LIVE_VARIABLE)); + assert!(ids_named_by(&module.debug_names).contains(&LIVE_VARIABLE)); + } + + #[test] + fn the_sweep_reaches_a_fixed_point_in_one_pass() { + let mut module = module_with_one_stranded_descriptor(); + assert!(drop_unreferenced_global_variables(&mut module)); + // Nothing left to remove, so a pipeline that runs it at more than one boundary pays a scan + // and changes nothing. + assert!(!drop_unreferenced_global_variables(&mut module)); + } + #[test] fn gc_keeps_local_pointer_store_sentinel_rooted_by_typed_sidecar() { let ulong = 1; diff --git a/tests/live_module_scope_variables.rs b/tests/live_module_scope_variables.rs new file mode 100644 index 000000000..fa12d3907 --- /dev/null +++ b/tests/live_module_scope_variables.rs @@ -0,0 +1,185 @@ +//! A translated module declares no global variable it never uses. +//! +//! A module-scope `OpVariable` is not inert bookkeeping. A `StorageBuffer` or `UniformConstant` one +//! carries `DescriptorSet` and `Binding` decorations and sits in the entry point's interface, which +//! is where a consumer that builds a `VkDescriptorSetLayout` from the module reads its +//! requirements. A variable that outlived its last use therefore becomes a descriptor the shader +//! never touches but the application still has to bind. +//! +//! Nothing catches that on its own. `finalize` filters the interface to the variables the bodies +//! reference — but the instruction-deleting work that runs after it (pointer and access-chain +//! closures, dead-value elimination, constant-CFG pruning, CFG construction) can delete the last +//! use of a variable that was live when the interface was written, and from that point the +//! arrangement is self-sustaining: the global collector roots liveness AT the entry-point +//! interface, so the interface entry keeps the variable alive and the variable justifies the +//! interface entry. `passes::drop_unreferenced_global_variables` breaks that cycle at each +//! boundary; this file is the end-to-end check that no boundary is missing one. +//! +//! `prune.rs` already states this standard for blocks — "Dead code is a defect regardless of the +//! consumer" — and prunes unreachable ones on every translate path. This is the same standard for +//! module-scope variables. + +use metal2vulkan::passes::Stage; +use metal2vulkan::{disassemble, translate_sanitized_native}; +use std::path::{Path, PathBuf}; + +/// Every global `OpVariable` the module declares that no instruction inside a function names. +/// +/// Reads the crate's own disassembly rather than the SPIR-V words: it prints raw ids and one +/// instruction per line, and the module-scope section is exactly what precedes the first +/// `OpFunction`. Function-scope (`Function` storage class) variables are declared after that line +/// and are deliberately out of scope here — they are local slots, not interface or descriptor +/// declarations. +fn global_variables_no_instruction_references(spirv: &[u8]) -> Vec { + let text = disassemble(spirv).expect("disassemble the translated module"); + let mut declared: Vec<(String, String)> = Vec::new(); + let mut referenced: Vec = Vec::new(); + let mut inside_a_function = false; + for line in text.lines() { + let tokens = line.split_whitespace().collect::>(); + if tokens.contains(&"OpFunction") { + inside_a_function = true; + } + if inside_a_function { + referenced.extend( + tokens + .iter() + .filter(|token| is_id(token)) + .map(|token| (*token).to_string()), + ); + continue; + } + // `% = OpVariable % ` + if let ([id, "=", "OpVariable", ..], Some(_)) = (tokens.as_slice(), tokens.get(4)) { + if is_id(id) { + declared.push(((*id).to_string(), line.trim().to_string())); + } + } + } + declared + .into_iter() + .filter(|(id, _)| !referenced.contains(id)) + .map(|(_, line)| line) + .collect() +} + +/// A raw SPIR-V id as the crate's disassembler prints it: `%` and decimal digits, no friendly name. +fn is_id(token: &str) -> bool { + token.strip_prefix('%').is_some_and(|digits| { + !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) + }) +} + +/// Scratch for one subject. `spirv-val` writes a fixed file name inside it and these tests run +/// concurrently, so each subject gets its own directory. +fn scratch(label: &str) -> PathBuf { + let directory = std::env::temp_dir().join(format!( + "m2v_live_globals_{}_{}", + std::process::id(), + label.replace(['/', '.'], "_") + )); + std::fs::create_dir_all(&directory).expect("scratch directory"); + directory +} + +/// How many global variables the sweep saw. A guard that inspected modules with no global variables +/// at all would pass on anything, so the callers below require this to be substantial. +fn assert_no_unused_globals(label: &str, spirv: &[u8]) -> usize { + let unused = global_variables_no_instruction_references(spirv); + assert!( + unused.is_empty(), + "{label} declares {} module-scope variable(s) no instruction references:\n {}", + unused.len(), + unused.join("\n ") + ); + disassemble(spirv) + .expect("disassemble the translated module") + .lines() + .take_while(|line| !line.split_whitespace().any(|token| token == "OpFunction")) + .filter(|line| line.split_whitespace().any(|token| token == "OpVariable")) + .count() +} + +#[test] +fn no_public_fixture_translates_to_a_module_with_an_unused_global_variable() { + let mut variables = 0; + let mut checked = 0; + for path in public_fixtures() { + let source = std::fs::read_to_string(&path).expect("read fixture"); + let label = path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let Some(stage) = stage_of(&source) else { + continue; + }; + let Ok(spirv) = translate_sanitized_native(&source, stage, &scratch(&label)) else { + continue; + }; + variables += assert_no_unused_globals(&label, &spirv); + checked += 1; + } + assert!( + checked >= 20 && variables >= 40, + "only {checked} fixtures with {variables} global variables were inspected, so this swept \ + almost nothing" + ); +} + +/// The same contract for every stage each fixture translates under. +/// +/// The stage is an input like any other, and translating a fixture under a stage its AIR does not +/// declare reaches interface paths the declared stage never does — a buffer parameter the declared +/// stage binds to a descriptor becomes an unbound Private placeholder under another. Those +/// placeholder rewrites are exactly the kind that replace a variable's last use. +#[test] +fn no_fixture_leaves_an_unused_global_variable_under_any_stage_it_translates_under() { + let mut variables = 0; + let mut checked = 0; + for path in public_fixtures() { + let source = std::fs::read_to_string(&path).expect("read fixture"); + let name = path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + for stage in [Stage::Vertex, Stage::Fragment, Stage::Kernel] { + let label = format!("{name}-{stage:?}"); + let Ok(spirv) = translate_sanitized_native(&source, stage, &scratch(&label)) else { + continue; + }; + variables += assert_no_unused_globals(&label, &spirv); + checked += 1; + } + } + assert!( + checked >= 30 && variables >= 60, + "only {checked} fixture/stage pairs with {variables} global variables were inspected, so \ + this swept almost nothing" + ); +} + +/// The stage the AIR declares. The library's `detect_stage` sanitizes from a file path; these +/// fixtures are already sanitized text, and they name their stage the same way. +fn stage_of(source: &str) -> Option { + if source.contains("!air.vertex =") { + Some(Stage::Vertex) + } else if source.contains("!air.fragment =") { + Some(Stage::Fragment) + } else if source.contains("!air.kernel =") { + Some(Stage::Kernel) + } else { + None + } +} + +fn public_fixtures() -> Vec { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("validation/fixtures/public"); + let mut paths = std::fs::read_dir(&root) + .unwrap_or_else(|error| panic!("read {}: {error}", root.display())) + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| path.extension().is_some_and(|extension| extension == "ll")) + .collect::>(); + paths.sort(); + paths +}