diff --git a/bend2/comp.ts b/bend2/comp.ts index bec68f3d4..49b5719ff 100644 --- a/bend2/comp.ts +++ b/bend2/comp.ts @@ -2260,7 +2260,8 @@ function emit_unfold(sc: Scope, m: Spine): HTerm | null { || term_strip(a).$ === "Var" ? null : { p: probe("a"), v: Bend.Ann(a, doms[i][2]) }); const bad = (y: HTerm): boolean => y.$ === "Lam" || mat_head(y) - || lets.some((l) => l?.p === y && term_any(l.v, bad)); + || lets.some((l) => l && (l.p === y ? term_any(l.v, bad) + : rest_use([b], l.p) === 0)); let xs = fs.map((a, i) => lets[i]?.p ?? a); let b = h; let hit = fs.every((a, i) => !m.live[i] || term_const(a)); diff --git a/tests/reg/unfold_drop_arg.bend b/tests/reg/unfold_drop_arg.bend new file mode 100644 index 000000000..882a1c0d1 --- /dev/null +++ b/tests/reg/unfold_drop_arg.bend @@ -0,0 +1,25 @@ +# regression witness: emit_unfold folded a call whose literal selector picked +# an arm that does not use a live, non-constant argument, and the dead let it +# wrapped around the arm was dropped, so the C lane never evaluated the +# argument: it printed 100 where the interpreter and JS evaluate boom and stop +# at the Nat wall. The unfold is now refused when a probe is unused. +import Base + +def boom(+k: Nat) -> Nat: + Nat.mul(Nat.mul(k, k), Nat.mul(k, k)) + +def pick(x: Nat, y: Nat, z: Nat) -> Nat: + match y: + case 0n: + z + case 1n+p: + x + +def main() -> IO(Unit): + do IO: + args : List <- IO.args() + +k : Nat = Nat.add(100000n, List.length(&1, String, args)) + IO.print(Nat.show(pick(boom(k), 0n, 100n))) + +#|bend: a Nat past the largest immediate 2^48-1 +#|exit 1 diff --git a/tests/reg/unfold_drop_arg_run.bend b/tests/reg/unfold_drop_arg_run.bend new file mode 100644 index 000000000..641fa0ee5 --- /dev/null +++ b/tests/reg/unfold_drop_arg_run.bend @@ -0,0 +1,23 @@ +# control for unfold_drop_arg: the same call with a run-time zero selector is +# not unfolded, so every lane already evaluated boom before the fix. Only the +# selector's constness differs from the regression test. +import Base + +def boom(+k: Nat) -> Nat: + Nat.mul(Nat.mul(k, k), Nat.mul(k, k)) + +def pick(x: Nat, y: Nat, z: Nat) -> Nat: + match y: + case 0n: + z + case 1n+p: + x + +def main() -> IO(Unit): + do IO: + args : List <- IO.args() + +k : Nat = Nat.add(100000n, List.length(&1, String, args)) + IO.print(Nat.show(pick(boom(k), Nat.sub(k, k), 100n))) + +#|bend: a Nat past the largest immediate 2^48-1 +#|exit 1