diff --git a/src/native/cfg/structured_emit/mod.rs b/src/native/cfg/structured_emit/mod.rs index 5f2fc0660..8d9a8e10d 100644 --- a/src/native/cfg/structured_emit/mod.rs +++ b/src/native/cfg/structured_emit/mod.rs @@ -57,6 +57,8 @@ mod multi_exit; pub(in crate::native) use multi_exit::*; mod phi_util; pub(in crate::native) use phi_util::*; +mod rewrite; +pub(in crate::native) use rewrite::*; // The own-arm and loop-exit-sibling paths consume the construct-tree planner core. The bounded // dispatcher materializers are also the typed source-level fallback for modest rejected CFGs. #[allow(dead_code)] diff --git a/src/native/cfg/structured_emit/multi_exit.rs b/src/native/cfg/structured_emit/multi_exit.rs index 49531af65..4b8f4bfe3 100644 --- a/src/native/cfg/structured_emit/multi_exit.rs +++ b/src/native/cfg/structured_emit/multi_exit.rs @@ -42,79 +42,92 @@ pub(in crate::native) fn split_multi_exit_critical_edges( /// Split a region predecessor that branches to both dispatch targets, preserving destination phis. /// The returned edge blocks become the unambiguous predecessor/target pairs consumed by /// [`synth_two_target_dispatch`]. +/// +/// Declining leaves `blocks` byte-identical: the body runs against a staged copy that is +/// committed only on `Some` (see [`atomic_rewrite`]). pub(in crate::native) fn split_two_target_critical_edges( blocks: &mut Vec, region: &HashSet, exits: &[String], counter: &mut usize, ) -> Option> { - if exits.len() != 2 { - return None; - } - let mut splits: Vec<(String, Vec)> = Vec::new(); - - for block in blocks.iter().filter(|block| region.contains(&block.name)) { - let successors = block_successors(block); - let hit: Vec = exits - .iter() - .enumerate() - .filter_map(|(index, exit)| { - successors - .iter() - .any(|target| target == exit) - .then_some(index) - }) - .collect(); - if hit.len() < 2 { - continue; + atomic_rewrite(blocks, |blocks| { + if exits.len() != 2 { + return None; } - splits.push((block.name.clone(), hit)); - } - if splits.is_empty() { - return Some(Vec::new()); - } + let mut splits: Vec<(String, Vec)> = Vec::new(); - let mut edge_blocks = Vec::new(); - let mut edge_preds = Vec::new(); - for (source, targets) in splits { - let mut edges = Vec::with_capacity(targets.len()); - for index in targets { - let edge = format!("{EXIT_EDGE_PREFIX}{counter}"); - *counter += 1; - edges.push((index, edge)); + for block in blocks.iter().filter(|block| region.contains(&block.name)) { + let successors = block_successors(block); + let hit: Vec = exits + .iter() + .enumerate() + .filter_map(|(index, exit)| { + successors + .iter() + .any(|target| target == exit) + .then_some(index) + }) + .collect(); + if hit.len() < 2 { + continue; + } + splits.push((block.name.clone(), hit)); + } + if splits.is_empty() { + return Some(Vec::new()); } - let source_block = blocks.iter_mut().find(|b| b.name == source)?; - // Redirect the terminator on the carrier (typed dual of the former string redirect). - if let Some(t) = source_block.typed_mut() { + let mut edge_blocks = Vec::new(); + let mut edge_preds = Vec::new(); + for (source, targets) in splits { + let mut edges = Vec::with_capacity(targets.len()); + for index in targets { + let edge = format!("{EXIT_EDGE_PREFIX}{counter}"); + *counter += 1; + edges.push((index, edge)); + } + + let source_block = blocks.iter_mut().find(|b| b.name == source)?; + // Redirect the terminator on the carrier (typed dual of the former string redirect). + if let Some(t) = source_block.typed_mut() { + for (index, edge) in &edges { + t.redirect_successor(&exits[*index], edge); + } + } + for (index, edge) in &edges { - t.redirect_successor(&exits[*index], edge); + let exit = blocks.iter_mut().find(|b| b.name == exits[*index])?; + if let Some(t) = exit.typed_mut() { + t.rewrite_phi_predecessor(&source, edge); + } + let edge_lines = vec![format!("br label {}", exits[*index])]; + edge_blocks.push(BodyBlock { + typed: crate::native::tir::lower_block_carrier( + edge, + &edge_lines, + &std::collections::HashMap::new(), + ) + .map(Into::into), + name: edge.clone(), + role: role_for_name(edge), + }); + edge_preds.push((edge.clone(), *index)); } } - - for (index, edge) in &edges { - let exit = blocks.iter_mut().find(|b| b.name == exits[*index])?; - if let Some(t) = exit.typed_mut() { - t.rewrite_phi_predecessor(&source, edge); - } - let edge_lines = vec![format!("br label {}", exits[*index])]; - edge_blocks.push(BodyBlock { - typed: crate::native::tir::lower_block_carrier( - edge, - &edge_lines, - &std::collections::HashMap::new(), - ) - .map(Into::into), - name: edge.clone(), - role: role_for_name(edge), - }); - edge_preds.push((edge.clone(), *index)); - } - } - blocks.extend(edge_blocks); - Some(edge_preds) + blocks.extend(edge_blocks); + Some(edge_preds) + }) } +/// Structure a two-exit loop: split its critical exit edges, then funnel both exits through one +/// dispatch merge. The scope and SSA contract are documented on the two primitives this composes, +/// [`split_multi_exit_critical_edges`] and [`synth_two_target_dispatch`]. +/// +/// The critical-edge split necessarily runs BEFORE the dispatch proof — the proof needs one +/// unambiguous predecessor per exit — so a declined dispatch would otherwise report `None` having +/// already edited the caller's blocks. Declining leaves `blocks` byte-identical: the body runs +/// against a staged copy that is committed only on `Some` (see [`atomic_rewrite`]). pub(in crate::native) fn synth_multi_exit_merge( blocks: &mut Vec, forest: &LoopForest, @@ -122,325 +135,336 @@ pub(in crate::native) fn synth_multi_exit_merge( exits: &[String], counter: &mut usize, ) -> Option { - if exits.len() != 2 { - return None; - } - // Deterministic exit ordering (the forest's exit list order is traversal-dependent). - let mut exits = exits.to_vec(); - exits.sort(); - let exits = &exits[..]; - let critical_edge_preds = - split_multi_exit_critical_edges(blocks, forest, header, exits, counter)?; - let body: HashSet<&str> = forest - .loop_for_header(header)? - .body - .iter() - .map(String::as_str) - .collect(); - - // For each in-loop block, the single exit index it branches to (bail if a block targets both). - let mut preds: Vec<(String, usize)> = Vec::new(); - let critical_edge_set: HashSet<&str> = critical_edge_preds - .iter() - .map(|(name, _)| name.as_str()) - .collect(); - for b in blocks.iter() { - if !body.contains(b.name.as_str()) && !critical_edge_set.contains(b.name.as_str()) { - continue; + atomic_rewrite(blocks, |blocks| { + if exits.len() != 2 { + return None; } - let mut hit: Option = None; - for succ in block_successors(b) { - if let Some(idx) = exits.iter().position(|e| e == &succ) { - match hit { - Some(prev) if prev != idx => return None, - _ => hit = Some(idx), + // Deterministic exit ordering (the forest's exit list order is traversal-dependent). + let mut exits = exits.to_vec(); + exits.sort(); + let exits = &exits[..]; + let critical_edge_preds = + split_multi_exit_critical_edges(blocks, forest, header, exits, counter)?; + let body: HashSet<&str> = forest + .loop_for_header(header)? + .body + .iter() + .map(String::as_str) + .collect(); + + // For each in-loop block, the single exit index it branches to (bail if a block targets both). + let mut preds: Vec<(String, usize)> = Vec::new(); + let critical_edge_set: HashSet<&str> = critical_edge_preds + .iter() + .map(|(name, _)| name.as_str()) + .collect(); + for b in blocks.iter() { + if !body.contains(b.name.as_str()) && !critical_edge_set.contains(b.name.as_str()) { + continue; + } + let mut hit: Option = None; + for succ in block_successors(b) { + if let Some(idx) = exits.iter().position(|e| e == &succ) { + match hit { + Some(prev) if prev != idx => return None, + _ => hit = Some(idx), + } } } + if let Some(idx) = hit { + preds.push((b.name.clone(), idx)); + } } - if let Some(idx) = hit { - preds.push((b.name.clone(), idx)); + if preds.is_empty() { + return None; } - } - if preds.is_empty() { - return None; - } - synth_two_target_dispatch(blocks, exits, &preds, counter) + synth_two_target_dispatch(blocks, exits, &preds, counter) + }) } /// Funnel a proved set of predecessor edges to two structural role targets through one typed /// dispatch block. The caller owns region discovery; this primitive owns the edge and SSA contract. +/// +/// Declining leaves `blocks` byte-identical: the body runs against a staged copy that is +/// committed only on `Some` (see [`atomic_rewrite`]). pub(in crate::native) fn synth_two_target_dispatch( blocks: &mut Vec, exits: &[String], preds: &[(String, usize)], counter: &mut usize, ) -> Option { - if exits.len() != 2 || preds.is_empty() || preds.iter().any(|(_, exit)| *exit >= exits.len()) { - return None; - } - let merge = format!("{SPLIT_PREFIX}{counter}"); - *counter += 1; - let sel = format!("{EXIT_SEL_PREFIX}{counter}"); - *counter += 1; - - // Redirecting several exits through one dispatch merge changes SSA dominance even though the - // selected runtime path is unchanged. A value defined on one exit path used to dominate that - // exit directly; after funneling, the other exit paths also reach the dispatch block and make the - // original definition non-dominating. Carry each such ordinary live-in through a typed phi in the - // dispatch (`undef` on paths selected for the other exit), then rewrite only the dominated target - // region's non-phi consumers. Destination phis retain their separate edge-specific funnel below. - let forest = analyze(blocks); - let mut definitions = HashMap::new(); - for block in blocks.iter() { - let carrier = block.typed.as_ref()?; - for instruction in &carrier.insts { - if let (Some(result), Some(ty)) = (&instruction.result, &instruction.result_ty) { - definitions.insert(result.clone(), (block.name.clone(), ty.clone())); - } + atomic_rewrite(blocks, |blocks| { + if exits.len() != 2 + || preds.is_empty() + || preds.iter().any(|(_, exit)| *exit >= exits.len()) + { + return None; } - } - let mut dispatch_live_phis: Vec<( - String, - crate::native::ir::LlType, - Vec<(crate::native::ir::LlValue, String)>, - )> = Vec::new(); - let mut region_substitutions = Vec::new(); - for (exit_index, exit) in exits.iter().enumerate() { - let region = blocks - .iter() - .filter(|block| forest.dominates(exit, &block.name)) - .map(|block| block.name.clone()) - .collect::>(); - let mut used = Vec::new(); - let mut used_set = HashSet::new(); - for block in blocks.iter().filter(|block| region.contains(&block.name)) { + let merge = format!("{SPLIT_PREFIX}{counter}"); + *counter += 1; + let sel = format!("{EXIT_SEL_PREFIX}{counter}"); + *counter += 1; + + // Redirecting several exits through one dispatch merge changes SSA dominance even though the + // selected runtime path is unchanged. A value defined on one exit path used to dominate that + // exit directly; after funneling, the other exit paths also reach the dispatch block and make the + // original definition non-dominating. Carry each such ordinary live-in through a typed phi in the + // dispatch (`undef` on paths selected for the other exit), then rewrite only the dominated target + // region's non-phi consumers. Destination phis retain their separate edge-specific funnel below. + let forest = analyze(blocks); + let mut definitions = HashMap::new(); + for block in blocks.iter() { let carrier = block.typed.as_ref()?; - for instruction in carrier - .insts - .iter() - .filter(|instruction| !instruction.is_phi()) - { - instruction.visit_uses(|name| { - if used_set.insert(name.to_string()) { - used.push(name.to_string()); - } - }); - } - let terminator_use = match &carrier.terminator { - crate::native::tir::TirTerminator::Br(_) - | crate::native::tir::TirTerminator::Ret(None) - | crate::native::tir::TirTerminator::Unreachable => None, - crate::native::tir::TirTerminator::BrCond { cond, .. } - | crate::native::tir::TirTerminator::Switch { selector: cond, .. } - | crate::native::tir::TirTerminator::Ret(Some(cond)) => Some(cond), - }; - if let Some(name) = terminator_use { - if used_set.insert(name.clone()) { - used.push(name.clone()); + for instruction in &carrier.insts { + if let (Some(result), Some(ty)) = (&instruction.result, &instruction.result_ty) { + definitions.insert(result.clone(), (block.name.clone(), ty.clone())); } } } - - let mut substitutions = HashMap::new(); - for value in used { - let Some((definition_block, ty)) = definitions.get(&value) else { - continue; - }; - if region.contains(definition_block) { - continue; - } - if preds + let mut dispatch_live_phis: Vec<( + String, + crate::native::ir::LlType, + Vec<(crate::native::ir::LlValue, String)>, + )> = Vec::new(); + let mut region_substitutions = Vec::new(); + for (exit_index, exit) in exits.iter().enumerate() { + let region = blocks .iter() - .all(|(predecessor, _)| forest.dominates(definition_block, predecessor)) - { - continue; + .filter(|block| forest.dominates(exit, &block.name)) + .map(|block| block.name.clone()) + .collect::>(); + let mut used = Vec::new(); + let mut used_set = HashSet::new(); + for block in blocks.iter().filter(|block| region.contains(&block.name)) { + let carrier = block.typed.as_ref()?; + for instruction in carrier + .insts + .iter() + .filter(|instruction| !instruction.is_phi()) + { + instruction.visit_uses(|name| { + if used_set.insert(name.to_string()) { + used.push(name.to_string()); + } + }); + } + let terminator_use = match &carrier.terminator { + crate::native::tir::TirTerminator::Br(_) + | crate::native::tir::TirTerminator::Ret(None) + | crate::native::tir::TirTerminator::Unreachable => None, + crate::native::tir::TirTerminator::BrCond { cond, .. } + | crate::native::tir::TirTerminator::Switch { selector: cond, .. } + | crate::native::tir::TirTerminator::Ret(Some(cond)) => Some(cond), + }; + if let Some(name) = terminator_use { + if used_set.insert(name.clone()) { + used.push(name.clone()); + } + } } - if !preds - .iter() - .filter(|(_, target)| *target == exit_index) - .all(|(predecessor, _)| forest.dominates(definition_block, predecessor)) - || !dispatch_live_value_type(ty) - { - return None; - } - let carried = format!("%metal2vulkan.exitlive.{counter}"); - *counter += 1; - let incoming = preds - .iter() - .map(|(predecessor, target)| { - let incoming = if *target == exit_index { - crate::native::ir::LlValue::Local(value.clone()) - } else { - crate::native::ir::LlValue::Undef - }; - (incoming, predecessor.clone()) - }) - .collect(); - substitutions.insert( - value, - crate::native::ir::TypedValue { - ty: ty.clone(), - value: crate::native::ir::LlValue::Local(carried.clone()), - }, - ); - dispatch_live_phis.push((carried, ty.clone(), incoming)); - } - region_substitutions.push((region, substitutions)); - } - // Apply only after every region/type/dominance proof succeeds, so a declined dispatch leaves the - // caller's owned CFG untouched. - for (region, substitutions) in region_substitutions { - for block in blocks - .iter_mut() - .filter(|block| region.contains(&block.name)) - { - block - .typed_mut() - .expect("dispatch live-in analysis checked every carrier") - .substitute_non_phi_values(&substitutions); - } - } - // Redirect every in-loop exit edge directly to the merge. - for b in blocks.iter_mut() { - if let Some((_, idx)) = preds.iter().find(|(n, _)| n == &b.name) { - if let Some(t) = b.typed_mut() { - t.redirect_successor(&exits[*idx], &merge); - } - } - } - - // After the in-loop redirect, body blocks no longer target the exits — only outer preds remain on - // each exit. `M` branches DIRECTLY to both real exits and funnels each exit's phis via the single - // `M` edge (`exit_edge_pred[i]` = `M`). When an exit is ALSO reached from OUTSIDE the loop body (an - // outer edge), `M` does not dominate it, so the dispatch selection cannot use it as a private arm — - // the M2 `selection:cross-arm-shared` residual (`02/590c6cf2`). That shared-exit privatization is - // done by the caller [`privatize_dispatch_shared_exits`] - // by cloning the exit's dominated forward region into an `M`-dominated copy; a bare pass-through - // trampoline is NOT enough because the shared exit block itself stays non-dominated (dead-end #6). - let dispatch_targets = [exits[0].clone(), exits[1].clone()]; - let exit_edge_pred = [merge.clone(), merge.clone()]; - - // For each exit that carries phis, funnel the redirected predecessors' incomings through a fresh - // value phi in the merge `M` and rewrite the exit phi to take that merged value via the single - // dispatch edge (from `M` directly, or from the private trampoline when the exit is shared). - // `M` branches to BOTH dispatch targets, so each value phi must cover ALL of `M`'s predecessors: - // the real incoming for the predecessors targeting THIS exit, and `undef` for those targeting - // the other exit (dynamically unreachable here — the selector routes them out the other side). - // STEP-1 (kb "STEP-1/STEP-2 decomposition"): drive the merge `M`'s value-phi carriers and each exit - // phi's carrier rebuild from the exit blocks' TYPED incomings rather than re-lowering the rewritten - // `.lines` text, so `M`'s carrier no longer depends on the `.lines` field. `carrier_ok` is all-or- - // nothing over ALL funnelled value phis: any funnelled exit phi whose carrier `phi_incoming` did not - // lower (aggregate → `None`, routes to retry) forces the full text fallback for `M`. Byte-identical - // either way (each `phi_edit` primitive has a `== re-lower` unit test; BC drift NONE proves it - // broadly). - // Drive the funnel off each exit block's TYPED carrier (line order preserved by `t.insts`). For each - // exit phi with an incoming from an in-loop predecessor rerouted to `M` for THIS exit, mint `M`'s - // value phi (over ALL of `M`'s preds — the redirected value for a pred targeting THIS exit, `undef` - // otherwise) and rewrite the exit phi to `kept + [ merged, edge_pred ]`. Aggregate phis - // (`phi_incoming: None`) carry no typed incoming list, so they are skipped — such a phi fails primary - // emit → retry regardless (the carrier is the sole emission substrate). Each primitive has a - // `== re-lower` unit test. - type TypedIncomings = Vec<(crate::native::ir::LlValue, String)>; - // `M`'s value phis, in the order the exit phis are visited: (merged name, phi type, incomings/ALL preds). - let mut typed_value_phis: Vec<(String, crate::native::ir::LlType, TypedIncomings)> = Vec::new(); - for (ei, e) in exits.iter().enumerate() { - let Some(exit_idx) = blocks.iter().position(|b| &b.name == e) else { - continue; - }; - let edge_pred = exit_edge_pred[ei].clone(); - // (exit phi dst, kept + `[merged, edge_pred]` typed incomings). - let mut exit_typed_merges: Vec<(String, TypedIncomings)> = Vec::new(); - if let Some(t) = &blocks[exit_idx].typed { - for inst in &t.insts { - let (Some(dst), Some((cty, inc))) = - (inst.result.clone(), inst.phi_incoming().clone()) - else { + let mut substitutions = HashMap::new(); + for value in used { + let Some((definition_block, ty)) = definitions.get(&value) else { continue; }; - // Redirected incomings: from an in-loop predecessor we rerouted to `M` for THIS exit. - let is_this_exit_pred = - |p: &str| preds.iter().any(|(name, idx)| name == p && *idx == ei); - let (typed_red, mut kept_plus): (Vec<_>, Vec<_>) = - inc.into_iter().partition(|(_, p)| is_this_exit_pred(p)); - if typed_red.is_empty() { + if region.contains(definition_block) { continue; } - let merged = format!("%metal2vulkan.exitphi.{counter}"); - *counter += 1; - // `M`'s value phi covers ALL of `M`'s preds: the redirected value for a pred targeting - // THIS exit, `undef` for one targeting the other exit (dynamically unreachable). - let merged_typed: TypedIncomings = preds + if preds .iter() - .map(|(pname, pidx)| { - let v = if *pidx == ei { - typed_red - .iter() - .find(|(_, p)| p == pname) - .map(|(v, _)| v.clone()) - .unwrap_or(crate::native::ir::LlValue::Undef) + .all(|(predecessor, _)| forest.dominates(definition_block, predecessor)) + { + continue; + } + if !preds + .iter() + .filter(|(_, target)| *target == exit_index) + .all(|(predecessor, _)| forest.dominates(definition_block, predecessor)) + || !dispatch_live_value_type(ty) + { + return None; + } + let carried = format!("%metal2vulkan.exitlive.{counter}"); + *counter += 1; + let incoming = preds + .iter() + .map(|(predecessor, target)| { + let incoming = if *target == exit_index { + crate::native::ir::LlValue::Local(value.clone()) } else { crate::native::ir::LlValue::Undef }; - (v, pname.clone()) + (incoming, predecessor.clone()) }) .collect(); - // Predecessor label is `edge_pred` (`M`, or the private trampoline); `merged` is defined - // in `M` which dominates both. Outer incomings stay on `kept_plus`. - kept_plus.push(( - crate::native::ir::LlValue::Local(merged.clone()), - edge_pred.clone(), - )); - exit_typed_merges.push((dst, kept_plus)); - typed_value_phis.push((merged, cty, merged_typed)); + substitutions.insert( + value, + crate::native::ir::TypedValue { + ty: ty.clone(), + value: crate::native::ir::LlValue::Local(carried.clone()), + }, + ); + dispatch_live_phis.push((carried, ty.clone(), incoming)); + } + region_substitutions.push((region, substitutions)); + } + // Apply only after every region/type/dominance proof succeeds, so a declined dispatch leaves the + // caller's owned CFG untouched. + for (region, substitutions) in region_substitutions { + for block in blocks + .iter_mut() + .filter(|block| region.contains(&block.name)) + { + block + .typed_mut() + .expect("dispatch live-in analysis checked every carrier") + .substitute_non_phi_values(&substitutions); } } - if let Some(t) = blocks[exit_idx].typed_mut() { - for (dst, kept_plus) in &exit_typed_merges { - t.set_phi_incomings(dst, kept_plus); + + // Redirect every in-loop exit edge directly to the merge. + for b in blocks.iter_mut() { + if let Some((_, idx)) = preds.iter().find(|(n, _)| n == &b.name) { + if let Some(t) = b.typed_mut() { + t.redirect_successor(&exits[*idx], &merge); + } } } - } - // Merge block: the funnelled value phis (if any), then an i1 selector phi (true = exit 0, false = - // exit 1) over its redirected predecessors, then a conditional branch to the (possibly - // trampoline-privatized) dispatch targets. Build `M`'s carrier by pushing the typed value phis then - // the i1 selector phi onto a fresh conditional-branch carrier (value phis precede the selector; - // each `push_value_phi` is byte-identical to lowering the printed phi line). - let selector_typed: TypedIncomings = preds - .iter() - .map(|(name, idx)| (crate::native::ir::LlValue::Bool(*idx == 0), name.clone())) - .collect(); - let branch_line = format!( - "br i1 {sel}, label {}, label {}", - dispatch_targets[0], dispatch_targets[1] - ); - let mut blk = crate::native::tir::lower_block_carrier( - &merge, - &[branch_line], - &std::collections::HashMap::new(), - )?; - for (mname, ty, merged_typed) in &typed_value_phis { - blk.push_value_phi(mname, ty, merged_typed); - } - for (name, ty, incoming) in &dispatch_live_phis { - blk.push_value_phi(name, ty, incoming); - } - blk.push_value_phi(&sel, &crate::native::ir::LlType::Int(1), &selector_typed); - let merge_block = BodyBlock { - name: merge.clone(), - role: role_for_name(&merge), - typed: Some(blk.into()), - }; - // Place it just before the first exit target so it sits in a natural position. - let insert_at = blocks - .iter() - .position(|b| b.name == exits[0] || b.name == exits[1]) - .unwrap_or(blocks.len()); - blocks.insert(insert_at, merge_block); + // After the in-loop redirect, body blocks no longer target the exits — only outer preds remain on + // each exit. `M` branches DIRECTLY to both real exits and funnels each exit's phis via the single + // `M` edge (`exit_edge_pred[i]` = `M`). When an exit is ALSO reached from OUTSIDE the loop body (an + // outer edge), `M` does not dominate it, so the dispatch selection cannot use it as a private arm — + // the M2 `selection:cross-arm-shared` residual (`02/590c6cf2`). That shared-exit privatization is + // done by the caller [`privatize_dispatch_shared_exits`] + // by cloning the exit's dominated forward region into an `M`-dominated copy; a bare pass-through + // trampoline is NOT enough because the shared exit block itself stays non-dominated (dead-end #6). + let dispatch_targets = [exits[0].clone(), exits[1].clone()]; + let exit_edge_pred = [merge.clone(), merge.clone()]; - Some(merge) + // For each exit that carries phis, funnel the redirected predecessors' incomings through a fresh + // value phi in the merge `M` and rewrite the exit phi to take that merged value via the single + // dispatch edge (from `M` directly, or from the private trampoline when the exit is shared). + // `M` branches to BOTH dispatch targets, so each value phi must cover ALL of `M`'s predecessors: + // the real incoming for the predecessors targeting THIS exit, and `undef` for those targeting + // the other exit (dynamically unreachable here — the selector routes them out the other side). + // STEP-1 (kb "STEP-1/STEP-2 decomposition"): drive the merge `M`'s value-phi carriers and each exit + // phi's carrier rebuild from the exit blocks' TYPED incomings rather than re-lowering the rewritten + // `.lines` text, so `M`'s carrier no longer depends on the `.lines` field. `carrier_ok` is all-or- + // nothing over ALL funnelled value phis: any funnelled exit phi whose carrier `phi_incoming` did not + // lower (aggregate → `None`, routes to retry) forces the full text fallback for `M`. Byte-identical + // either way (each `phi_edit` primitive has a `== re-lower` unit test; BC drift NONE proves it + // broadly). + // Drive the funnel off each exit block's TYPED carrier (line order preserved by `t.insts`). For each + // exit phi with an incoming from an in-loop predecessor rerouted to `M` for THIS exit, mint `M`'s + // value phi (over ALL of `M`'s preds — the redirected value for a pred targeting THIS exit, `undef` + // otherwise) and rewrite the exit phi to `kept + [ merged, edge_pred ]`. Aggregate phis + // (`phi_incoming: None`) carry no typed incoming list, so they are skipped — such a phi fails primary + // emit → retry regardless (the carrier is the sole emission substrate). Each primitive has a + // `== re-lower` unit test. + type TypedIncomings = Vec<(crate::native::ir::LlValue, String)>; + // `M`'s value phis, in the order the exit phis are visited: (merged name, phi type, incomings/ALL preds). + let mut typed_value_phis: Vec<(String, crate::native::ir::LlType, TypedIncomings)> = + Vec::new(); + for (ei, e) in exits.iter().enumerate() { + let Some(exit_idx) = blocks.iter().position(|b| &b.name == e) else { + continue; + }; + let edge_pred = exit_edge_pred[ei].clone(); + // (exit phi dst, kept + `[merged, edge_pred]` typed incomings). + let mut exit_typed_merges: Vec<(String, TypedIncomings)> = Vec::new(); + if let Some(t) = &blocks[exit_idx].typed { + for inst in &t.insts { + let (Some(dst), Some((cty, inc))) = + (inst.result.clone(), inst.phi_incoming().clone()) + else { + continue; + }; + // Redirected incomings: from an in-loop predecessor we rerouted to `M` for THIS exit. + let is_this_exit_pred = + |p: &str| preds.iter().any(|(name, idx)| name == p && *idx == ei); + let (typed_red, mut kept_plus): (Vec<_>, Vec<_>) = + inc.into_iter().partition(|(_, p)| is_this_exit_pred(p)); + if typed_red.is_empty() { + continue; + } + let merged = format!("%metal2vulkan.exitphi.{counter}"); + *counter += 1; + // `M`'s value phi covers ALL of `M`'s preds: the redirected value for a pred targeting + // THIS exit, `undef` for one targeting the other exit (dynamically unreachable). + let merged_typed: TypedIncomings = preds + .iter() + .map(|(pname, pidx)| { + let v = if *pidx == ei { + typed_red + .iter() + .find(|(_, p)| p == pname) + .map(|(v, _)| v.clone()) + .unwrap_or(crate::native::ir::LlValue::Undef) + } else { + crate::native::ir::LlValue::Undef + }; + (v, pname.clone()) + }) + .collect(); + // Predecessor label is `edge_pred` (`M`, or the private trampoline); `merged` is defined + // in `M` which dominates both. Outer incomings stay on `kept_plus`. + kept_plus.push(( + crate::native::ir::LlValue::Local(merged.clone()), + edge_pred.clone(), + )); + exit_typed_merges.push((dst, kept_plus)); + typed_value_phis.push((merged, cty, merged_typed)); + } + } + if let Some(t) = blocks[exit_idx].typed_mut() { + for (dst, kept_plus) in &exit_typed_merges { + t.set_phi_incomings(dst, kept_plus); + } + } + } + + // Merge block: the funnelled value phis (if any), then an i1 selector phi (true = exit 0, false = + // exit 1) over its redirected predecessors, then a conditional branch to the (possibly + // trampoline-privatized) dispatch targets. Build `M`'s carrier by pushing the typed value phis then + // the i1 selector phi onto a fresh conditional-branch carrier (value phis precede the selector; + // each `push_value_phi` is byte-identical to lowering the printed phi line). + let selector_typed: TypedIncomings = preds + .iter() + .map(|(name, idx)| (crate::native::ir::LlValue::Bool(*idx == 0), name.clone())) + .collect(); + let branch_line = format!( + "br i1 {sel}, label {}, label {}", + dispatch_targets[0], dispatch_targets[1] + ); + let mut blk = crate::native::tir::lower_block_carrier( + &merge, + &[branch_line], + &std::collections::HashMap::new(), + )?; + for (mname, ty, merged_typed) in &typed_value_phis { + blk.push_value_phi(mname, ty, merged_typed); + } + for (name, ty, incoming) in &dispatch_live_phis { + blk.push_value_phi(name, ty, incoming); + } + blk.push_value_phi(&sel, &crate::native::ir::LlType::Int(1), &selector_typed); + let merge_block = BodyBlock { + name: merge.clone(), + role: role_for_name(&merge), + typed: Some(blk.into()), + }; + // Place it just before the first exit target so it sits in a natural position. + let insert_at = blocks + .iter() + .position(|b| b.name == exits[0] || b.name == exits[1]) + .unwrap_or(blocks.len()); + blocks.insert(insert_at, merge_block); + + Some(merge) + }) } fn dispatch_live_value_type(ty: &crate::native::ir::LlType) -> bool { @@ -465,116 +489,219 @@ fn dispatch_live_value_type(ty: &crate::native::ir::LlType) -> bool { /// Scope: the caller gates on a pure `[MultipleLatches]` loop. Returns `None` (leaving the loop /// unstructured for the fallback) if a latch's terminator does not actually name the header among its /// successors — so a well-formed redirect is always possible when it returns `Some`. +/// +/// Declining leaves `blocks` byte-identical: the body runs against a staged copy that is +/// committed only on `Some` (see [`atomic_rewrite`]). pub(in crate::native) fn synth_multi_latch_continue( blocks: &mut Vec, header: &str, latches: &[String], counter: &mut usize, ) -> Option { - if latches.len() < 2 { - return None; - } - let mut latches = latches.to_vec(); - latches.sort(); - latches.dedup(); - let latch_set: HashSet<&str> = latches.iter().map(String::as_str).collect(); - - // Every latch must currently branch to the header (a back-edge). If one does not, we cannot cleanly - // isolate its back-edge, so bail and leave the loop for the fallback. - for l in &latches { - let b = blocks.iter().find(|b| &b.name == l)?; - if !block_successors(b).iter().any(|s| s == header) { + atomic_rewrite(blocks, |blocks| { + if latches.len() < 2 { return None; } - } + let mut latches = latches.to_vec(); + latches.sort(); + latches.dedup(); + let latch_set: HashSet<&str> = latches.iter().map(String::as_str).collect(); - let hidx = blocks.iter().position(|b| b.name == header)?; - let new_latch = format!("{SPLIT_PREFIX}{counter}"); - *counter += 1; - - // Header phi surgery, driven off the header block's TYPED carrier (line order preserved by `t.insts`). - // For each header phi with a latch (redirected) incoming, mint a merged value phi in `L` over ALL - // latches (`undef` for a latch this phi does not carry) and rewrite the header phi to - // `kept..., [ merged, L ]`. Aggregate phis (`phi_incoming: None`) carry no typed incoming list, so - // they are skipped — such a phi fails primary emit → retry regardless (the carrier is the sole - // emission substrate). Each primitive has a `== re-lower` unit test. - type TypedIncomings = Vec<(crate::native::ir::LlValue, String)>; - // `L`'s value phis, in the order the header phis are visited: (merged name, phi type, over ALL latches). - let mut typed_value_phis: Vec<(String, crate::native::ir::LlType, TypedIncomings)> = Vec::new(); - // (header phi dst, kept + `[merged, L]` typed incomings). - let mut header_typed_merges: Vec<(String, TypedIncomings)> = Vec::new(); - if let Some(t) = &blocks[hidx].typed { - for inst in &t.insts { - let (Some(dst), Some((cty, inc))) = (inst.result.clone(), inst.phi_incoming().clone()) - else { - continue; - }; - let (typed_red, mut kept_plus): (Vec<_>, Vec<_>) = inc - .into_iter() - .partition(|(_, p)| latch_set.contains(p.as_str())); - if typed_red.is_empty() { - continue; - } - let merged = format!("%metal2vulkan.latchphi.{counter}"); - *counter += 1; - // Every latch now branches to `L`, so the merged phi covers ALL of them (a latch missing - // from this phi's incomings gets `undef` — it does not carry this value on its back-edge). - let merged_typed: TypedIncomings = latches - .iter() - .map(|lname| { - let v = typed_red - .iter() - .find(|(_, p)| p == lname) - .map(|(v, _)| v.clone()) - .unwrap_or(crate::native::ir::LlValue::Undef); - (v, lname.clone()) - }) - .collect(); - kept_plus.push(( - crate::native::ir::LlValue::Local(merged.clone()), - new_latch.clone(), - )); - header_typed_merges.push((dst, kept_plus)); - typed_value_phis.push((merged, cty, merged_typed)); - } - } - if let Some(t) = blocks[hidx].typed_mut() { - for (dst, kept_plus) in &header_typed_merges { - t.set_phi_incomings(dst, kept_plus); - } - } - - // Redirect each latch's header edge to the new single latch `L`. - for l in &latches { - if let Some(b) = blocks.iter_mut().find(|b| &b.name == l) { - if let Some(t) = b.typed_mut() { - t.redirect_successor(header, &new_latch); + // Every latch must currently branch to the header (a back-edge). If one does not, we cannot cleanly + // isolate its back-edge, so bail and leave the loop for the fallback. + for l in &latches { + let b = blocks.iter().find(|b| &b.name == l)?; + if !block_successors(b).iter().any(|s| s == header) { + return None; } } - } - // `L`: the funnelled value phis, then an unconditional branch back to the header. Insert it just - // before the header (or after it when the header is the function entry, keeping `blocks[0]` intact); - // `analyze` builds edges from terminators, so the vector position only matters for the entry. Build - // `L`'s carrier by pushing the typed merged phis onto a fresh `br label {header}` carrier - // (byte-identical to lowering the merged phi lines + terminator — `push_value_phi`'s `== re-lower`). - let insert_at = hidx.max(1); - let latch_block = { - let mut blk = crate::native::tir::lower_block_carrier( - &new_latch, - &[format!("br label {header}")], - &std::collections::HashMap::new(), - )?; - for (merged, ty, merged_typed) in &typed_value_phis { - blk.push_value_phi(merged, ty, merged_typed); - } - BodyBlock { - name: new_latch.clone(), - role: role_for_name(&new_latch), - typed: Some(blk.into()), - } - }; - blocks.insert(insert_at, latch_block); + let hidx = blocks.iter().position(|b| b.name == header)?; + let new_latch = format!("{SPLIT_PREFIX}{counter}"); + *counter += 1; - Some(new_latch) + // Header phi surgery, driven off the header block's TYPED carrier (line order preserved by `t.insts`). + // For each header phi with a latch (redirected) incoming, mint a merged value phi in `L` over ALL + // latches (`undef` for a latch this phi does not carry) and rewrite the header phi to + // `kept..., [ merged, L ]`. Aggregate phis (`phi_incoming: None`) carry no typed incoming list, so + // they are skipped — such a phi fails primary emit → retry regardless (the carrier is the sole + // emission substrate). Each primitive has a `== re-lower` unit test. + type TypedIncomings = Vec<(crate::native::ir::LlValue, String)>; + // `L`'s value phis, in the order the header phis are visited: (merged name, phi type, over ALL latches). + let mut typed_value_phis: Vec<(String, crate::native::ir::LlType, TypedIncomings)> = + Vec::new(); + // (header phi dst, kept + `[merged, L]` typed incomings). + let mut header_typed_merges: Vec<(String, TypedIncomings)> = Vec::new(); + if let Some(t) = &blocks[hidx].typed { + for inst in &t.insts { + let (Some(dst), Some((cty, inc))) = + (inst.result.clone(), inst.phi_incoming().clone()) + else { + continue; + }; + let (typed_red, mut kept_plus): (Vec<_>, Vec<_>) = inc + .into_iter() + .partition(|(_, p)| latch_set.contains(p.as_str())); + if typed_red.is_empty() { + continue; + } + let merged = format!("%metal2vulkan.latchphi.{counter}"); + *counter += 1; + // Every latch now branches to `L`, so the merged phi covers ALL of them (a latch missing + // from this phi's incomings gets `undef` — it does not carry this value on its back-edge). + let merged_typed: TypedIncomings = latches + .iter() + .map(|lname| { + let v = typed_red + .iter() + .find(|(_, p)| p == lname) + .map(|(v, _)| v.clone()) + .unwrap_or(crate::native::ir::LlValue::Undef); + (v, lname.clone()) + }) + .collect(); + kept_plus.push(( + crate::native::ir::LlValue::Local(merged.clone()), + new_latch.clone(), + )); + header_typed_merges.push((dst, kept_plus)); + typed_value_phis.push((merged, cty, merged_typed)); + } + } + if let Some(t) = blocks[hidx].typed_mut() { + for (dst, kept_plus) in &header_typed_merges { + t.set_phi_incomings(dst, kept_plus); + } + } + + // Redirect each latch's header edge to the new single latch `L`. + for l in &latches { + if let Some(b) = blocks.iter_mut().find(|b| &b.name == l) { + if let Some(t) = b.typed_mut() { + t.redirect_successor(header, &new_latch); + } + } + } + + // `L`: the funnelled value phis, then an unconditional branch back to the header. Insert it just + // before the header (or after it when the header is the function entry, keeping `blocks[0]` intact); + // `analyze` builds edges from terminators, so the vector position only matters for the entry. Build + // `L`'s carrier by pushing the typed merged phis onto a fresh `br label {header}` carrier + // (byte-identical to lowering the merged phi lines + terminator — `push_value_phi`'s `== re-lower`). + let insert_at = hidx.max(1); + let latch_block = { + let mut blk = crate::native::tir::lower_block_carrier( + &new_latch, + &[format!("br label {header}")], + &std::collections::HashMap::new(), + )?; + for (merged, ty, merged_typed) in &typed_value_phis { + blk.push_value_phi(merged, ty, merged_typed); + } + BodyBlock { + name: new_latch.clone(), + role: role_for_name(&new_latch), + typed: Some(blk.into()), + } + }; + blocks.insert(insert_at, latch_block); + + Some(new_latch) + }) +} + +#[cfg(test)] +mod tests { + use super::super::test_support::bb; + use super::*; + + /// A block with no terminator does not lower, so it carries no typed substrate. Production sees + /// these (`BodyBlock::typed` is documented `None` only for a block whose lines did not lower); + /// the dispatch funnel declines on the first one it meets. + fn bb_uncarried(name: &str) -> BodyBlock { + let block = bb(name, &[]); + assert!(block.typed.is_none(), "fixture must have no typed carrier"); + block + } + + /// The rewrite family's contract is that a decline leaves the caller's CFG untouched. + /// `split_two_target_critical_edges` redirects the source terminator to the fresh edge blocks + /// BEFORE it has proved every dispatch target exists; when a target is missing it declines with + /// the redirect already applied and the edge blocks never inserted, so the source names + /// successors that are not in the function at all. + #[test] + fn declined_critical_edge_split_leaves_no_dangling_successor() { + let mut blocks = vec![ + bb("%entry", &["br i1 %c, label %x, label %y"]), + bb("%x", &["ret void"]), + ]; + let before = format!("{blocks:?}"); + let region = HashSet::from(["%entry".to_string()]); + let exits = vec!["%x".to_string(), "%y".to_string()]; + let mut counter = 0; + + assert!( + split_two_target_critical_edges(&mut blocks, ®ion, &exits, &mut counter).is_none(), + "a dispatch target with no block cannot be split" + ); + let names: HashSet<&str> = blocks.iter().map(|b| b.name.as_str()).collect(); + let entry = blocks.iter().find(|b| b.name == "%entry").unwrap(); + for successor in block_successors(entry) { + assert!( + names.contains(successor.as_str()) || successor == "%y", + "declined split left %entry branching to {successor}, which is not a block" + ); + } + assert_eq!( + format!("{blocks:?}"), + before, + "a declined split must not edit the CFG" + ); + } + + /// The composite: the two-exit funnel splits the loop's critical exit edges first and only then + /// runs the dispatch proof, so a declined dispatch used to hand its caller a mutated block list + /// while reporting `None`. `forest_loop_merges` reads that as "nothing changed" and keeps using + /// its cached `LoopForest`, which no longer describes the graph. + #[test] + fn declined_two_exit_funnel_leaves_the_split_edges_out() { + let mut blocks = vec![ + bb("%entry", &["br label %h"]), + bb("%h", &["br i1 %c0, label %b, label %latch"]), + // In the loop body (it reaches the latch) and branching to BOTH exits, so the funnel + // must split its critical exit edges before it can name one predecessor per exit. + bb( + "%b", + &["switch i32 %s, label %latch [ i32 0, label %x i32 1, label %y ]"], + ), + bb("%latch", &["br i1 %c1, label %h, label %x"]), + bb("%x", &["ret void"]), + bb("%y", &["ret void"]), + // Reached by nothing, but the dispatch proof walks every block, so this is what makes + // the funnel decline — after the critical-edge split has already edited the list. + bb_uncarried("%uncarried"), + ]; + let forest = analyze(&blocks); + let exits = forest + .loop_for_header("%h") + .map(|l| { + let mut exits = l.exits.clone(); + exits.sort(); + exits + }) + .expect("the fixture's natural loop"); + assert_eq!(exits, vec!["%x".to_string(), "%y".to_string()]); + let before = format!("{blocks:?}"); + let mut counter = 0; + + assert!( + synth_multi_exit_merge(&mut blocks, &forest, "%h", &exits, &mut counter).is_none(), + "the dispatch proof declines on the uncarried block" + ); + assert_eq!( + format!("{blocks:?}"), + before, + "a declined funnel must not leave its critical-edge splits behind" + ); + } } diff --git a/src/native/cfg/structured_emit/phi_util.rs b/src/native/cfg/structured_emit/phi_util.rs index d70efee43..3abbe8fdd 100644 --- a/src/native/cfg/structured_emit/phi_util.rs +++ b/src/native/cfg/structured_emit/phi_util.rs @@ -44,6 +44,9 @@ pub(in crate::native) fn privatize_dispatch_shared_exits( /// phi in the shared `exit` is rewritten: incomings from the redirected (inner-loop) predecessors are /// merged into a fresh phi in the synthesized pass-through block, and the `exit` phi replaces those /// incomings with a single `[merged, %passthrough]` pair while keeping the enclosing loop's incomings. +/// +/// Declining leaves `blocks` byte-identical: the body runs against a staged copy that is +/// committed only on `Some` (see [`atomic_rewrite`]). pub(in crate::native) fn split_phi_overlap( blocks: &mut Vec, forest: &LoopForest, @@ -51,99 +54,102 @@ pub(in crate::native) fn split_phi_overlap( exit: &str, counter: &mut usize, ) -> Option { - let body: Vec = forest.loop_for_header(header)?.body.clone(); - let preds: Vec = body - .iter() - .filter(|name| { - blocks - .iter() - .find(|b| &b.name == *name) - .map(|b| block_successors(b).iter().any(|s| s == exit)) - .unwrap_or(false) - }) - .cloned() - .collect(); - if preds.is_empty() { - return None; - } - let is_redirected = |pred: &str| preds.iter().any(|p| p == pred); - - let new_name = format!("{SPLIT_PREFIX}{counter}"); - *counter += 1; - - let exit_idx = blocks.iter().position(|b| b.name == exit)?; - // Drive the exit-phi surgery off the exit block's TYPED carrier (line order preserved by `t.insts`). - // For each phi with a redirected incoming, mint a merged pass-through phi over the redirected typed - // incomings and rewrite the exit phi to `kept + [ merged, {new_name} ]`. Aggregate phis - // (`phi_incoming: None`) carry no typed incoming list, so they are skipped here — such a phi fails - // primary emit and routes to retry regardless (the carrier is the sole emission substrate), so the - // primary path never emits this block. Each primitive has a `== re-lower` unit test. - type TypedIncomings = Vec<(crate::native::ir::LlValue, String)>; - // (merged pass-through phi name, phi type, redirected typed incomings). - let mut passthrough_merges: Vec<(String, crate::native::ir::LlType, TypedIncomings)> = - Vec::new(); - // (exit phi dst, kept typed incomings + the `[ merged, {new_name} ]` funnel). - let mut exit_rewrites: Vec<(String, TypedIncomings)> = Vec::new(); - if let Some(t) = &blocks[exit_idx].typed { - for inst in &t.insts { - let (Some(dst), Some((ty, inc))) = (inst.result.clone(), inst.phi_incoming().clone()) - else { - continue; - }; - let (typed_red, mut kept_plus): (Vec<_>, Vec<_>) = - inc.into_iter().partition(|(_, pred)| is_redirected(pred)); - if typed_red.is_empty() { - continue; - } - let merged = format!("{new_name}.phi{}", passthrough_merges.len()); - kept_plus.push(( - crate::native::ir::LlValue::Local(merged.clone()), - new_name.clone(), - )); - passthrough_merges.push((merged, ty, typed_red)); - exit_rewrites.push((dst, kept_plus)); + atomic_rewrite(blocks, |blocks| { + let body: Vec = forest.loop_for_header(header)?.body.clone(); + let preds: Vec = body + .iter() + .filter(|name| { + blocks + .iter() + .find(|b| &b.name == *name) + .map(|b| block_successors(b).iter().any(|s| s == exit)) + .unwrap_or(false) + }) + .cloned() + .collect(); + if preds.is_empty() { + return None; } - } - if let Some(t) = blocks[exit_idx].typed_mut() { - for (dst, kept_plus) in &exit_rewrites { - t.set_phi_incomings(dst, kept_plus); - } - } + let is_redirected = |pred: &str| preds.iter().any(|p| p == pred); - // Redirect the inner-loop predecessors' terminators from `exit` to the pass-through. - for b in blocks.iter_mut() { - if preds.iter().any(|p| p == &b.name) { - if let Some(t) = b.typed_mut() { - t.redirect_successor(exit, &new_name); + let new_name = format!("{SPLIT_PREFIX}{counter}"); + *counter += 1; + + let exit_idx = blocks.iter().position(|b| b.name == exit)?; + // Drive the exit-phi surgery off the exit block's TYPED carrier (line order preserved by `t.insts`). + // For each phi with a redirected incoming, mint a merged pass-through phi over the redirected typed + // incomings and rewrite the exit phi to `kept + [ merged, {new_name} ]`. Aggregate phis + // (`phi_incoming: None`) carry no typed incoming list, so they are skipped here — such a phi fails + // primary emit and routes to retry regardless (the carrier is the sole emission substrate), so the + // primary path never emits this block. Each primitive has a `== re-lower` unit test. + type TypedIncomings = Vec<(crate::native::ir::LlValue, String)>; + // (merged pass-through phi name, phi type, redirected typed incomings). + let mut passthrough_merges: Vec<(String, crate::native::ir::LlType, TypedIncomings)> = + Vec::new(); + // (exit phi dst, kept typed incomings + the `[ merged, {new_name} ]` funnel). + let mut exit_rewrites: Vec<(String, TypedIncomings)> = Vec::new(); + if let Some(t) = &blocks[exit_idx].typed { + for inst in &t.insts { + let (Some(dst), Some((ty, inc))) = + (inst.result.clone(), inst.phi_incoming().clone()) + else { + continue; + }; + let (typed_red, mut kept_plus): (Vec<_>, Vec<_>) = + inc.into_iter().partition(|(_, pred)| is_redirected(pred)); + if typed_red.is_empty() { + continue; + } + let merged = format!("{new_name}.phi{}", passthrough_merges.len()); + kept_plus.push(( + crate::native::ir::LlValue::Local(merged.clone()), + new_name.clone(), + )); + passthrough_merges.push((merged, ty, typed_red)); + exit_rewrites.push((dst, kept_plus)); + } + } + if let Some(t) = blocks[exit_idx].typed_mut() { + for (dst, kept_plus) in &exit_rewrites { + t.set_phi_incomings(dst, kept_plus); } } - } - // Insert the pass-through block: merged phis followed by the branch to the original exit. Build its - // carrier by pushing the typed merged phis onto a fresh `br label {exit}` carrier (byte-identical to - // lowering the merged phi lines + terminator — `push_value_phi`'s `== re-lower` test). - let insert_at = blocks - .iter() - .position(|b| b.name == exit) - .unwrap_or(blocks.len()); - let mut blk = crate::native::tir::lower_block_carrier( - &new_name, - &[format!("br label {exit}")], - &std::collections::HashMap::new(), - )?; - for (merged, ty, typed_red) in &passthrough_merges { - blk.push_value_phi(merged, ty, typed_red); - } - blocks.insert( - insert_at, - BodyBlock { - name: new_name.clone(), - role: role_for_name(&new_name), - typed: Some(blk.into()), - }, - ); + // Redirect the inner-loop predecessors' terminators from `exit` to the pass-through. + for b in blocks.iter_mut() { + if preds.iter().any(|p| p == &b.name) { + if let Some(t) = b.typed_mut() { + t.redirect_successor(exit, &new_name); + } + } + } - Some(new_name) + // Insert the pass-through block: merged phis followed by the branch to the original exit. Build its + // carrier by pushing the typed merged phis onto a fresh `br label {exit}` carrier (byte-identical to + // lowering the merged phi lines + terminator — `push_value_phi`'s `== re-lower` test). + let insert_at = blocks + .iter() + .position(|b| b.name == exit) + .unwrap_or(blocks.len()); + let mut blk = crate::native::tir::lower_block_carrier( + &new_name, + &[format!("br label {exit}")], + &std::collections::HashMap::new(), + )?; + for (merged, ty, typed_red) in &passthrough_merges { + blk.push_value_phi(merged, ty, typed_red); + } + blocks.insert( + insert_at, + BodyBlock { + name: new_name.clone(), + role: role_for_name(&new_name), + typed: Some(blk.into()), + }, + ); + + Some(new_name) + }) } /// True if `name`'s block has a phi node (an instruction of the form `%x = phi ...`). Reads the typed diff --git a/src/native/cfg/structured_emit/rewrite.rs b/src/native/cfg/structured_emit/rewrite.rs new file mode 100644 index 000000000..d1e30a67e --- /dev/null +++ b/src/native/cfg/structured_emit/rewrite.rs @@ -0,0 +1,35 @@ +//! The structurizer's CFG-rewrite discipline. + +use super::BodyBlock; + +/// Run a CFG rewrite that is allowed to decline, guaranteeing the caller's block list is untouched +/// when it does. +/// +/// Every `synth_*`/`split_*` primitive in this module advertises the same contract — "anything +/// outside this scope returns `None`, leaving the loop unstructured so `structured_plan` falls +/// back" — and callers depend on it. [`forest_loop_merges`](super::forest_loop_merges) only +/// invalidates its cached [`LoopForest`](super::LoopForest) when a primitive reports `Some`, and a +/// declined loop's blocks are handed straight to the next construction attempt. +/// +/// Honoring that by hand means proving, for every `?` in a rewrite body, that it cannot fire after +/// the first edit. That is not a property a reviewer can check by reading, and not one a later edit +/// preserves. Three primitives here had it wrong: `split_two_target_critical_edges` could redirect a +/// source terminator and then bail, leaving an edge pointing at a block it never inserted, and +/// `synth_multi_latch_continue` could rewrite a header's phis onto a latch it then failed to build. +/// +/// So the rewrite runs against a private copy and the caller's list is replaced only on `Some`. +/// [`BodyBlock`] holds its instruction payload behind an `Arc`, so that copy is a vector of +/// (name, role, pointer) and only the blocks the rewrite actually edits are deep-copied — the same +/// copy-on-write `typed_mut` already performs on every edit. +/// +/// A name counter borrowed by `rewrite` is deliberately *not* rolled back: names a declined attempt +/// consumed stay consumed, so every synthesized name remains unique across attempts. +pub(in crate::native) fn atomic_rewrite( + blocks: &mut Vec, + rewrite: impl FnOnce(&mut Vec) -> Option, +) -> Option { + let mut staged = blocks.clone(); + let outcome = rewrite(&mut staged)?; + *blocks = staged; + Some(outcome) +} diff --git a/src/native/cfg/structured_emit/selection_merge.rs b/src/native/cfg/structured_emit/selection_merge.rs index ca470be0e..88e354401 100644 --- a/src/native/cfg/structured_emit/selection_merge.rs +++ b/src/native/cfg/structured_emit/selection_merge.rs @@ -659,6 +659,9 @@ pub(in crate::native) fn header_owned_merge_predecessors( /// that case redirect the owned predecessor around the gateway and copy the gateway's phi value onto /// the new predecessor edge. If outside control still enters the gateway, its original natural-phi /// incoming remains; otherwise the private merge replaces it completely. +/// +/// Declining leaves `blocks` byte-identical: the body runs against a staged copy that is +/// committed only on `Some` (see [`atomic_rewrite`]). pub(in crate::native) fn synth_unique_selection_merge_phi_explicit( blocks: &mut Vec, preds: &[String], @@ -666,135 +669,138 @@ pub(in crate::native) fn synth_unique_selection_merge_phi_explicit( routes_into_natural: &HashSet, counter: &mut usize, ) -> Option { - let pred_set = preds.iter().map(String::as_str).collect::>(); - let mut redirects = Vec::<(String, String)>::new(); - for block in blocks.iter() { - if !pred_set.contains(block.name.as_str()) { - continue; - } - for target in block_successors(block) { - if target == natural || routes_into_natural.contains(&target) { - redirects.push((block.name.clone(), target)); + atomic_rewrite(blocks, |blocks| { + let pred_set = preds.iter().map(String::as_str).collect::>(); + let mut redirects = Vec::<(String, String)>::new(); + for block in blocks.iter() { + if !pred_set.contains(block.name.as_str()) { + continue; + } + for target in block_successors(block) { + if target == natural || routes_into_natural.contains(&target) { + redirects.push((block.name.clone(), target)); + } } } - } - if redirects.is_empty() { - return None; - } + if redirects.is_empty() { + return None; + } - let direct_preds = redirects - .iter() - .filter(|(_, target)| target == natural) - .map(|(pred, _)| pred.as_str()) - .collect::>(); - let route_preds = redirects - .iter() - .filter(|(_, target)| target != natural) - .fold( - HashMap::<&str, Vec<&str>>::new(), - |mut map, (pred, route)| { - map.entry(route.as_str()).or_default().push(pred.as_str()); - map + let direct_preds = redirects + .iter() + .filter(|(_, target)| target == natural) + .map(|(pred, _)| pred.as_str()) + .collect::>(); + let route_preds = redirects + .iter() + .filter(|(_, target)| target != natural) + .fold( + HashMap::<&str, Vec<&str>>::new(), + |mut map, (pred, route)| { + map.entry(route.as_str()).or_default().push(pred.as_str()); + map + }, + ); + let route_has_unredirected_predecessor = |route: &str| { + blocks.iter().any(|block| { + !pred_set.contains(block.name.as_str()) + && block_successors(block).iter().any(|target| target == route) + }) + }; + + let new_name = format!("{SPLIT_PREFIX}{SEL_TOKEN}{counter}"); + *counter += 1; + + // Rebuild `natural`'s phis: the redirected predecessors' incomings fold into a merged phi in the + // pass-through; the rest stay, plus one `[merged, pass-through]` incoming. Driven off `natural`'s + // TYPED carrier (line order preserved by `t.insts`). Aggregate phis (`phi_incoming: None`) carry no + // typed incoming list, so they are skipped — such a phi fails primary emit → retry regardless (the + // carrier is the sole emission substrate). Each primitive has a `== re-lower` unit test (kb + // "STEP-1/STEP-2 decomposition"). + let nat_idx = blocks.iter().position(|b| b.name == natural)?; + type TypedIncomings = Vec<(crate::native::ir::LlValue, String)>; + // (merged pass-through phi name, phi type, redirected typed incomings). + let mut passthrough_merges: Vec<(String, crate::native::ir::LlType, TypedIncomings)> = + Vec::new(); + // (nat phi dst, kept typed incomings + the `[ merged, {new_name} ]` funnel). + let mut nat_rewrites: Vec<(String, TypedIncomings)> = Vec::new(); + if let Some(t) = &blocks[nat_idx].typed { + for inst in &t.insts { + let (Some(dst), Some((ty, inc))) = + (inst.result.clone(), inst.phi_incoming().clone()) + else { + continue; + }; + let mut typed_red = Vec::new(); + let mut kept_plus = Vec::new(); + for (value, predecessor) in inc { + if direct_preds.contains(predecessor.as_str()) { + typed_red.push((value, predecessor)); + continue; + } + if let Some(owned_preds) = route_preds.get(predecessor.as_str()) { + typed_red.extend( + owned_preds + .iter() + .map(|owned| (value.clone(), (*owned).to_string())), + ); + if route_has_unredirected_predecessor(&predecessor) { + kept_plus.push((value, predecessor)); + } + continue; + } + kept_plus.push((value, predecessor)); + } + if typed_red.is_empty() { + continue; + } + let merged = format!("{new_name}.phi{}", passthrough_merges.len()); + kept_plus.push(( + crate::native::ir::LlValue::Local(merged.clone()), + new_name.clone(), + )); + passthrough_merges.push((merged, ty, typed_red)); + nat_rewrites.push((dst, kept_plus)); + } + } + if let Some(t) = blocks[nat_idx].typed_mut() { + for (dst, kept_plus) in &nat_rewrites { + t.set_phi_incomings(dst, kept_plus); + } + } + + for (predecessor, old_target) in &redirects { + if let Some(block) = blocks.iter_mut().find(|block| block.name == *predecessor) { + block.typed_mut()?.redirect_successor(old_target, &new_name); + } + } + + let at = blocks + .iter() + .position(|b| b.name == natural) + .unwrap_or(blocks.len()); + // Pass-through block: build its carrier by pushing the typed merged phis onto a fresh + // `br label {natural}` carrier (byte-identical to lowering the merged phi lines + terminator — + // `push_value_phi`'s `== re-lower` test). + let mut blk = crate::native::tir::lower_block_carrier( + &new_name, + &[format!("br label {natural}")], + &std::collections::HashMap::new(), + )?; + for (merged, ty, typed_red) in &passthrough_merges { + blk.push_value_phi(merged, ty, typed_red); + } + blocks.insert( + at, + BodyBlock { + name: new_name.clone(), + role: role_for_name(&new_name), + typed: Some(blk.into()), }, ); - let route_has_unredirected_predecessor = |route: &str| { - blocks.iter().any(|block| { - !pred_set.contains(block.name.as_str()) - && block_successors(block).iter().any(|target| target == route) - }) - }; - let new_name = format!("{SPLIT_PREFIX}{SEL_TOKEN}{counter}"); - *counter += 1; - - // Rebuild `natural`'s phis: the redirected predecessors' incomings fold into a merged phi in the - // pass-through; the rest stay, plus one `[merged, pass-through]` incoming. Driven off `natural`'s - // TYPED carrier (line order preserved by `t.insts`). Aggregate phis (`phi_incoming: None`) carry no - // typed incoming list, so they are skipped — such a phi fails primary emit → retry regardless (the - // carrier is the sole emission substrate). Each primitive has a `== re-lower` unit test (kb - // "STEP-1/STEP-2 decomposition"). - let nat_idx = blocks.iter().position(|b| b.name == natural)?; - type TypedIncomings = Vec<(crate::native::ir::LlValue, String)>; - // (merged pass-through phi name, phi type, redirected typed incomings). - let mut passthrough_merges: Vec<(String, crate::native::ir::LlType, TypedIncomings)> = - Vec::new(); - // (nat phi dst, kept typed incomings + the `[ merged, {new_name} ]` funnel). - let mut nat_rewrites: Vec<(String, TypedIncomings)> = Vec::new(); - if let Some(t) = &blocks[nat_idx].typed { - for inst in &t.insts { - let (Some(dst), Some((ty, inc))) = (inst.result.clone(), inst.phi_incoming().clone()) - else { - continue; - }; - let mut typed_red = Vec::new(); - let mut kept_plus = Vec::new(); - for (value, predecessor) in inc { - if direct_preds.contains(predecessor.as_str()) { - typed_red.push((value, predecessor)); - continue; - } - if let Some(owned_preds) = route_preds.get(predecessor.as_str()) { - typed_red.extend( - owned_preds - .iter() - .map(|owned| (value.clone(), (*owned).to_string())), - ); - if route_has_unredirected_predecessor(&predecessor) { - kept_plus.push((value, predecessor)); - } - continue; - } - kept_plus.push((value, predecessor)); - } - if typed_red.is_empty() { - continue; - } - let merged = format!("{new_name}.phi{}", passthrough_merges.len()); - kept_plus.push(( - crate::native::ir::LlValue::Local(merged.clone()), - new_name.clone(), - )); - passthrough_merges.push((merged, ty, typed_red)); - nat_rewrites.push((dst, kept_plus)); - } - } - if let Some(t) = blocks[nat_idx].typed_mut() { - for (dst, kept_plus) in &nat_rewrites { - t.set_phi_incomings(dst, kept_plus); - } - } - - for (predecessor, old_target) in &redirects { - if let Some(block) = blocks.iter_mut().find(|block| block.name == *predecessor) { - block.typed_mut()?.redirect_successor(old_target, &new_name); - } - } - - let at = blocks - .iter() - .position(|b| b.name == natural) - .unwrap_or(blocks.len()); - // Pass-through block: build its carrier by pushing the typed merged phis onto a fresh - // `br label {natural}` carrier (byte-identical to lowering the merged phi lines + terminator — - // `push_value_phi`'s `== re-lower` test). - let mut blk = crate::native::tir::lower_block_carrier( - &new_name, - &[format!("br label {natural}")], - &std::collections::HashMap::new(), - )?; - for (merged, ty, typed_red) in &passthrough_merges { - blk.push_value_phi(merged, ty, typed_red); - } - blocks.insert( - at, - BodyBlock { - name: new_name.clone(), - role: role_for_name(&new_name), - typed: Some(blk.into()), - }, - ); - - Some(new_name) + Some(new_name) + }) } /// Does the single-exit loop `header`'s merge block double as the natural selection merge