A declined CFG rewrite must hand back the CFG it was given
The structurizer's `synth_*`/`split_*` primitives all advertise the same contract —
`synth_two_target_dispatch` states it outright: "Apply only after every region/type/dominance
proof succeeds, so a declined dispatch leaves the caller's owned CFG untouched" — and callers
depend on it. `forest_loop_merges` only drops its cached `LoopForest` and selection-merge map when
a primitive reports `Some`; a decline that edited the blocks anyway leaves that cache describing a
graph that no longer exists, and every later header is planned against it.
Six primitives edit before their last proof. Two are reachable, and the new tests reach them:
- `split_two_target_critical_edges` redirects the source terminator to both fresh edge blocks
before it has checked that each dispatch target is a block. When one is not, it bails with the
redirect applied and the edge blocks never inserted — the source ends up naming successors that
are not in the function.
- `synth_multi_exit_merge` composes that split with the dispatch proof, and the split must run
first (the proof needs one unambiguous predecessor per exit). So any dispatch decline — an
uncarried block, a non-dominating live-in, a live-in whose type cannot cross the funnel — returns
`None` with the loop's critical exit edges already split.
The other four (`synth_two_target_dispatch`, `synth_multi_latch_continue`,
`synth_unique_selection_merge_phi_explicit`, `split_phi_overlap`) each stage their proofs correctly
and then leak on one trailing `lower_block_carrier(...)?` — the last of which would abandon phi
rewrites and edge redirects pointing at a merge block it failed to build. I could not author an
input that reaches any of them: they lower a fixed synthetic `br` line, which the codebase treats
as infallible elsewhere (`terminal_exit.rs` `.expect("synthetic conditional carrier is always
parseable")`). They are unreached today, not guaranteed.
That is the shape of the problem: the contract held only where someone had proved every `?` in a
body unreachable-after-the-first-edit. That is not a property a reviewer can check by reading, and
not one the next edit preserves. So `atomic_rewrite` now runs each of the six against a private
copy and commits it only on `Some`. `BodyBlock` keeps its payload behind an `Arc`, so the copy is a
vector of (name, role, pointer) and only blocks the rewrite actually edits are deep-copied — the
copy-on-write `typed_mut` already performs on every edit. A borrowed name counter is deliberately
not rolled back, so names a declined attempt consumed stay consumed and every synthesized name
stays unique across attempts.
Verified: 2880 corpus sources byte-identical against eac559d, so nothing currently observed took a
corrupting path. Slowest source (`fc78a004`, 44 blocks) 2.81s -> 2.85s, against a 20s ceiling.
`cargo fmt --all --check`, clippy `-D warnings`, `RUSTDOCFLAGS='-D warnings' cargo doc`,
`cargo test -p metal2vulkan` (debug and release, so the `bounded_growth` and `bounded_work` guards
ran), `cargo test -p metal2vulkan-validation`.
The diff reads large only because six bodies moved one level in; `git diff -w` is the wrapper.
This commit is contained in:
1 parent
eac559dcb3
commit
02c3f9e2a8
5 files changed
+822
-646
No files matched your search
@@ -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)]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<BodyBlock>,
|
||||
forest: &LoopForest,
|
||||
@@ -51,99 +54,102 @@ pub(in crate::native) fn split_phi_overlap(
|
||||
exit: &str,
|
||||
counter: &mut usize,
|
||||
) -> Option<String> {
|
||||
let body: Vec<String> = forest.loop_for_header(header)?.body.clone();
|
||||
let preds: Vec<String> = 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<String> = forest.loop_for_header(header)?.body.clone();
|
||||
let preds: Vec<String> = 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
|
||||
|
||||
@@ -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<T>(
|
||||
blocks: &mut Vec<BodyBlock>,
|
||||
rewrite: impl FnOnce(&mut Vec<BodyBlock>) -> Option<T>,
|
||||
) -> Option<T> {
|
||||
let mut staged = blocks.clone();
|
||||
let outcome = rewrite(&mut staged)?;
|
||||
*blocks = staged;
|
||||
Some(outcome)
|
||||
}
|
||||
@@ -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<BodyBlock>,
|
||||
preds: &[String],
|
||||
@@ -666,135 +669,138 @@ pub(in crate::native) fn synth_unique_selection_merge_phi_explicit(
|
||||
routes_into_natural: &HashSet<String>,
|
||||
counter: &mut usize,
|
||||
) -> Option<String> {
|
||||
let pred_set = preds.iter().map(String::as_str).collect::<HashSet<_>>();
|
||||
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::<HashSet<_>>();
|
||||
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::<HashSet<_>>();
|
||||
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::<HashSet<_>>();
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user