diff --git a/CHANGELOG.md b/CHANGELOG.md index e0dc25f..52b88ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ All notable changes to Puddi are recorded here. The format follows [Keep a Chang - `F32.from_bits` constructs a float from its 32-bit IEEE 754 representation. +### Changed + +- The optimizer removes unused value chains with tape-based liveness and keeps bounds traps when discarding scalar array reads. + ### Fixed - `pud doc` preserves paragraph breaks in module documentation. diff --git a/docs/architecture.md b/docs/architecture.md index 88133bf..4b9ce8a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -40,7 +40,7 @@ The prelude, standard modules and platform layer are embedded in the binary with **Elaboration** (`elab.rs`, `types.rs`, `exhaust.rs`, `ir.rs`). Type inference and checking of function bodies, and lowering to a typed IR in which every type is concrete. Generic functions are checked per instantiation and monomorphized: `elab.rs` keeps a queue of function instances, seeded with the entry points and exports, and elaborates each instance once. Implicit widening, `?` with `From`, `dyn Trait` coercions, closures and their captured variables, and async functions are all lowered here. `exhaust.rs` checks `match` exhaustiveness with the usefulness algorithm. -**Optimization** (`opt.rs`). Rewrites each function's IR before code generation: it inlines calls that receive a closure or a function value (so iterator chains and higher-order helpers become plain loops without `call_ref`), tiny functions, calls that match on a constructor argument (so `x.get(k).unwrap_or(0)` builds no `Option`), and the recursive calls of small recursive functions once; it then forwards immutable struct fields, selects `match` arms on known constructors and drops dead `let`s. `PUD_NO_OPT=1` skips it. +**Optimization** (`opt.rs`). Rewrites each function's IR before code generation. It inlines higher-order and tiny calls, calls that match on a constructor argument, and one level of small recursive calls. It also forwards immutable struct fields and selects `match` arms for known constructors. The [liveness tape](tape.md) removes unused values and retains required checks, including the bounds checks of discarded scalar array reads. `PUD_NO_OPT=1` skips optimization. **Code generation** (`codegen.rs`). Turns IR into WebAssembly text using WasmGC types, one function at a time on several threads (each with its own copy of the state, merged in function order): structs and enum variants become GC structs (enum variants are subtypes of a base struct), closures and trait objects are GC structs with function references, and integer overflow checks are inlined. `ranges.rs` tracks the value ranges of integer locals implied by `if` and `while` conditions, and codegen leaves out the overflow checks those ranges rule out. `asm.rs` assembles the text into a binary core module, encoding function bodies on several threads; it understands the subset of the text format codegen writes and falls back to the `wat` crate for anything else (`PUD_ASM_CHECK=1` checks that both give the same module). diff --git a/docs/tape.md b/docs/tape.md new file mode 100644 index 0000000..4f2ea6c --- /dev/null +++ b/docs/tape.md @@ -0,0 +1,32 @@ +# Tape-based liveness in Puddi IR + +Joshua Tenner's Tape design stores computations in an indexed arena of 16-byte records with side storage for larger payloads. The scheduler carries IDs. A computation can lose its place in the schedule while its ID stays valid. Separate nodes for values, effects and guards let a pass keep an observable trap even if the value that originally produced it is dead. His design also gives facts a validity region in the control-flow graph and uses a sparse B-tree for facts that need ordered lookup. [The Tape](https://jtenner.github.io/posts/2026-11-21-thetape/) · [Puddi discussion](https://github.com/puddi-lang/puddi/discussions/5#discussioncomment-19814867) + +## How Puddi applies the design + +Puddi's elaborated IR is a typed, structured tree with explicit local IDs, assignments, captures, branches and loops. Inlining and code generation use this structure directly. The optimizer builds a per-function liveness tape over that tree. During each cleanup, removable bindings have stable indices, a flat table stores their local dependencies, and a separate schedule records statement positions. The tree supplies the executable payloads and their order within each region. [Implementation](../src/opt/tape.rs) + +Demands start at retained expressions and include local reads, assignment targets and closure captures. An assignment can require the binding to initialize the captured local's box. The worklist follows each demanded local to its candidate definitions, including multiple bindings of a shared local ID, and visits each definition's operands once. Pattern destructuring and computations with unknown effects stay scheduled. The final walk removes dead statements and keeps the original order within each region. This is a mark-and-sweep formulation of the value liveness described in the proposal. LLVM's ADCE also propagates liveness from roots and additionally analyzes control dependence through its CFG. [LLVM ADCE](https://llvm.org/doxygen/ADCE_8cpp_source.html) + +A chain such as `let a = 42; let b = a; let c = b` used to require a full use-count and removal pass for each dead link. A chain of length `n` could therefore take quadratic work in that phase. The tape costs linear work per cleanup in IR nodes, local slots and recorded uses. The arena, operand table and schedule use temporary linear space. The cleanup runs after inlining rewrites and also runs when the first rewrite round leaves a function unchanged. These are algorithmic bounds. Actual compiler cost includes building the tape, walking the tree to apply it and running later optimization rounds. + +## Separating a read from its guard + +For an unused `let item = xs[i]` on a scalar list, Puddi keeps evaluation of the list and index, the source-level list check, and the backing array's Wasm check. The element fetch disappears from the successful path. The tape treats the operands as required by the guard and tracks demand for `item` independently. A live `item` still lowers to the regular `array.get`. An unused one lowers to the new `ArrayGuard` IR node. + +```text +Original After liveness +evaluate xs and i evaluate xs and i +check the list's logical length check the list's logical length +item = array_get(xs.data, i) ArrayGuard(xs.data, i) +``` + +The lowering evaluates the array and index once, in left-to-right order. It compares the index as unsigned against `array.len`, which also traps for a null array reference. This catches negative indices. The out-of-bounds branch executes the original typed Wasm get, so the engine reports the same bounds trap. Wasm traps before fetching an element on that branch. Reference-valued reads retain the ordinary get because Puddi also checks the loaded reference for null. [WebAssembly array instructions](https://webassembly.github.io/gc/core/exec/instructions.html) · [Lowering](../src/codegen.rs) + +In-bounds reads now access the length without loading the element. The guard introduces a branch and may use two scratch locals. A Wasm engine can already optimize some `array.get; drop` sequences, so the runtime and code-size tradeoffs depend on the engine and workload. The regression checks the emitted guard and execution behavior. It supplies no performance measurements. + +## Requirements for further Tape passes + +**Guard elimination.** Puddi's existing range analysis follows integer locals through structured branches to prove arithmetic checks safe. Removing a bounds guard requires a proof about the same index and the same backing array on every path reaching it. A comparison with a list's mutable logical length and a comparison with the backing array's length establish different facts. Assignments, aliasing and loop backedges determine where those facts remain valid. WebAssembly GC array length is fixed for an array instance, and a live `array.get` retains its engine-level check. A fact store becomes useful when several independent passes need to share proofs. [Integer range analysis](../src/ranges.rs) + +**Dead arguments.** Tenner's private parameter mask relies on demand propagation through direct calls and forwarding cycles. For Puddi, entry points, WIT exports, imports, function references, closure calls and trait shims constrain call signatures. A private direct-call implementation needs to prove eligibility for both caller and callee and keep the effects of argument evaluation in order. The current tape marks intraprocedural local demand and preserves the existing call ABI. diff --git a/src/codegen.rs b/src/codegen.rs index 37d1b94..16e9dcc 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -616,6 +616,21 @@ impl<'a> Cg<'a> { st.emit(&format!("call {n}")); } ExprKind::Intrinsic(name, targs, args) => self.gen_intrinsic(st, name, targs, args, &e.ty), + ExprKind::ArrayGuard(array, index) => { + let a = self.temp(st, &array.ty); + let i = self.temp(st, &index.ty); + self.gen_expr(st, array); + st.emit(&format!("local.set {a}")); + self.gen_expr(st, index); + st.emit(&format!("local.tee {i} local.get {a} array.len i32.ge_u if")); + // Take the original Wasm trap on failure. The in-bounds path reads only + // the array length, and both operands are evaluated exactly once. + let Ty::Array(elem) = &array.ty else { unreachable!("array guard requires an array") }; + let an = self.tname(&array.ty); + let op = self.array_get_op(elem, &an); + st.emit(&format!(" local.get {a} local.get {i} {op} drop")); + st.emit("end i32.const 0"); + } ExprKind::CallIndirect(f, args) => { let Ty::Fn(ps, r) = &f.ty else { st.emit("unreachable"); diff --git a/src/elab.rs b/src/elab.rs index 051cf9b..a8a503f 100644 --- a/src/elab.rs +++ b/src/elab.rs @@ -3200,7 +3200,7 @@ impl<'g, 'p> Elab<'g, 'p> { } } ExprKind::Field(b, _, _) => self.fin_expr(b, locals, reported), - ExprKind::SetField(b, _, v) => { + ExprKind::SetField(b, _, v) | ExprKind::ArrayGuard(b, v) => { self.fin_expr(b, locals, reported); self.fin_expr(v, locals, reported); } diff --git a/src/ir.rs b/src/ir.rs index 8dc7bd7..fd0b357 100644 --- a/src/ir.rs +++ b/src/ir.rs @@ -76,6 +76,8 @@ pub enum ExprKind { SetLocal(LocalId, Box), Call(FnInst, Vec), Intrinsic(String, Vec, Vec), + /// Check a scalar array read without fetching its element. Produces unit. + ArrayGuard(Box, Box), CallIndirect(Box, Vec), FnValue(FnInst), Closure { func: usize, captures: Vec }, diff --git a/src/opt.rs b/src/opt.rs index a2349fa..97db76d 100644 --- a/src/opt.rs +++ b/src/opt.rs @@ -19,6 +19,8 @@ use crate::elab::Global; use crate::ir::*; use crate::types::{AdtId, Ty}; +mod tape; + /// Largest callee (in IR nodes) that is inlined. const MAX_CALLEE: usize = 600; /// A function stops growing once it reaches this size. @@ -97,11 +99,13 @@ fn optimize(funcs: &[Option], insts: &HashMap, set_fields: o.analyze(&f.body, &f.params); o.changed = false; o.rewrite(&mut f.body); - if !o.changed { + if o.changed { + flatten(&mut f.body); + } + let removed = tape::eliminate(&mut f.body, o.locals.len()); + if !o.changed && !removed { break; } - flatten(&mut f.body); - while dead_lets(&mut f.body, o.locals.len()) {} o.size = size(&f.body); } f.locals = o.locals; @@ -555,6 +559,9 @@ fn flatten(e: &mut Expr) { } fn pure(e: &Expr) -> bool { + if e.ty == Ty::Never { + return false; + } match &e.kind { ExprKind::Lit(_) | ExprKind::Local(_) | ExprKind::FnValue(_) | ExprKind::Closure { .. } => true, ExprKind::StructNew(a) | ExprKind::TupleNew(a) | ExprKind::EnumNew(_, a) => a.iter().all(pure), @@ -562,31 +569,6 @@ fn pure(e: &Expr) -> bool { } } -/// Drops `let`s of unused locals and statements without effects; true if any was dropped. -fn dead_lets(body: &mut Expr, n: usize) -> bool { - let mut uses = vec![0u32; n]; - visit(body, &mut |e| match &e.kind { - ExprKind::Local(id) | ExprKind::SetLocal(id, _) => uses[*id] += 1, - ExprKind::Closure { captures, .. } => captures.iter().for_each(|c| uses[*c] += 1), - _ => {} - }); - let mut changed = false; - fn go(e: &mut Expr, uses: &[u32], changed: &mut bool) { - children_mut(e, &mut |c| go(c, uses, changed)); - if let ExprKind::Block(stmts, _) = &mut e.kind { - let before = stmts.len(); - stmts.retain(|s| match s { - Stmt::Let(Pat { kind: PatKind::Bind(id, None), .. }, x) => uses[*id] > 0 || !pure(x), - Stmt::Expr(x) => !pure(x), - _ => true, - }); - *changed |= stmts.len() != before; - } - } - go(body, &uses, &mut changed); - changed -} - // ---------------- traversal ---------------- pub fn visit(e: &Expr, f: &mut dyn FnMut(&Expr)) { @@ -612,7 +594,7 @@ fn children(e: &Expr, f: &mut dyn FnMut(&Expr)) { f(recv); args.iter().for_each(f); } - ExprKind::SetField(a, _, b) => { + ExprKind::SetField(a, _, b) | ExprKind::ArrayGuard(a, b) => { f(a); f(b); } @@ -661,7 +643,7 @@ fn children_mut(e: &mut Expr, f: &mut dyn FnMut(&mut Expr)) { f(recv); args.iter_mut().for_each(f); } - ExprKind::SetField(a, _, b) => { + ExprKind::SetField(a, _, b) | ExprKind::ArrayGuard(a, b) => { f(a); f(b); } diff --git a/src/opt/tape.rs b/src/opt/tape.rs new file mode 100644 index 0000000..eabdb77 --- /dev/null +++ b/src/opt/tape.rs @@ -0,0 +1,189 @@ +//! A function-local liveness tape over the structured IR. +//! +//! Values have stable indices and share a flat operand table. The statement +//! schedule follows the tree's control flow and can omit dead values without +//! changing their indices. Effects and control flow stay in their original order. + +use std::ops::Range; + +use crate::ir::{Expr, ExprKind, Lit, LocalId, Pat, PatKind, Stmt}; +use crate::types::{IntTy, Ty}; + +use super::{children, children_mut, pure, visit}; + +type NodeId = usize; + +struct Value { + operands: Range, + next_definition: Option, + live: bool, +} + +#[derive(Clone, Copy)] +enum Scheduled { + Keep, + Drop, + Value(NodeId), + /// The guard is required independently of demand for the element. + ArrayRead(Option), +} + +struct Tape { + values: Vec, + operands: Vec, + schedule: Vec, + definitions: Vec>, + pending: Vec, +} + +pub(super) fn eliminate(body: &mut Expr, locals: usize) -> bool { + let mut tape = Tape { + values: Vec::new(), + operands: Vec::new(), + schedule: Vec::new(), + definitions: vec![None; locals], + pending: Vec::new(), + }; + tape.collect(body); + tape.mark_live(); + let mut schedule = tape.schedule.iter().copied(); + let mut changed = false; + tape.compact(body, &mut schedule, &mut changed); + debug_assert!(schedule.next().is_none()); + changed +} + +impl Tape { + fn define(&mut self, local: LocalId, value: Option<&Expr>) -> NodeId { + let start = self.operands.len(); + if let Some(value) = value { + visit(value, &mut |e| local_uses(e, |id| self.operands.push(id))); + } + let id = self.values.len(); + self.values.push(Value { + operands: start..self.operands.len(), + next_definition: self.definitions[local].replace(id), + live: false, + }); + id + } + + fn collect(&mut self, e: &Expr) { + local_uses(e, |id| self.pending.push(id)); + if let ExprKind::Block(stmts, tail) = &e.kind { + for s in stmts { + let (binding, value, simple) = match s { + Stmt::Let(Pat { kind: PatKind::Bind(id, None), .. }, value) => (Some(*id), value, true), + Stmt::Let(Pat { kind: PatKind::Wild, .. }, value) | Stmt::Expr(value) => (None, value, true), + Stmt::Let(_, value) => (None, value, false), + }; + let action = if simple && pure(value) { + binding.map_or(Scheduled::Drop, |id| Scheduled::Value(self.define(id, Some(value)))) + } else if simple && scalar_array_read(value) { + Scheduled::ArrayRead(binding.map(|id| self.define(id, None))) + } else { + Scheduled::Keep + }; + self.schedule.push(action); + if matches!(action, Scheduled::Keep | Scheduled::ArrayRead(_)) { + self.collect(value); + } + } + if let Some(tail) = tail { + self.collect(tail); + } + } else { + children(e, &mut |child| self.collect(child)); + } + } + + fn mark_live(&mut self) { + while let Some(local) = self.pending.pop() { + // A local can have several reaching bindings in the structured IR. + // Conservatively demand every one and expand their operands once. + let mut id = self.definitions[local].take(); + while let Some(current) = id { + let value = &mut self.values[current]; + value.live = true; + self.pending.extend_from_slice(&self.operands[value.operands.clone()]); + id = value.next_definition; + } + } + } + + fn compact(&self, e: &mut Expr, schedule: &mut impl Iterator, changed: &mut bool) { + if let ExprKind::Block(stmts, tail) = &mut e.kind { + *stmts = std::mem::take(stmts) + .into_iter() + .filter_map(|mut stmt| { + let action = schedule.next().expect("each statement has a tape entry"); + if matches!(action, Scheduled::Drop) || matches!(action, Scheduled::Value(id) if !self.values[id].live) { + // Only pure subtrees, which contain no scheduled statements. + *changed = true; + return None; + } + let value = match &mut stmt { + Stmt::Let(_, value) | Stmt::Expr(value) => value, + }; + self.compact(value, schedule, changed); + if matches!(action, Scheduled::ArrayRead(id) if id.is_none_or(|id| !self.values[id].live)) { + let (Stmt::Let(_, mut value) | Stmt::Expr(mut value)) = stmt; + keep_array_guard(&mut value); + *changed = true; + return Some(Stmt::Expr(value)); + } + Some(stmt) + }) + .collect(); + if let Some(tail) = tail { + self.compact(tail, schedule, changed); + } + } else { + children_mut(e, &mut |child| self.compact(child, schedule, changed)); + if matches!(&e.kind, ExprKind::Discard(value) if scalar_array_read(value)) { + let ExprKind::Discard(value) = std::mem::replace(&mut e.kind, ExprKind::Lit(Lit::Unit)) else { + unreachable!() + }; + *e = *value; + keep_array_guard(e); + *changed = true; + } + } + } +} + +fn local_uses(e: &Expr, mut use_local: impl FnMut(LocalId)) { + match &e.kind { + ExprKind::Local(id) | ExprKind::SetLocal(id, _) => use_local(*id), + ExprKind::Closure { captures, .. } => captures.iter().copied().for_each(use_local), + _ => {} + } +} + +fn scalar_array_read(e: &Expr) -> bool { + if e.ty == Ty::Never { + return false; + } + match &e.kind { + ExprKind::Block(_, Some(tail)) => scalar_array_read(tail), + ExprKind::Intrinsic(name, _, args) if name == "array_get" => match args.as_slice() { + [Expr { ty: Ty::Array(elem), .. }, Expr { ty: Ty::Int(IntTy::I32), .. }] => { + matches!(elem.as_ref(), Ty::Int(_) | Ty::Float(_) | Ty::Bool | Ty::Char | Ty::Unit) + } + _ => false, + }, + _ => false, + } +} + +fn keep_array_guard(e: &mut Expr) { + e.ty = Ty::Unit; + match &mut e.kind { + ExprKind::Block(_, Some(tail)) => keep_array_guard(tail), + ExprKind::Intrinsic(_, _, args) => { + let [array, index]: [Expr; 2] = std::mem::take(args).try_into().expect("an array read has two operands"); + e.kind = ExprKind::ArrayGuard(Box::new(array), Box::new(index)); + } + _ => unreachable!("an array read was scheduled for its guard"), + } +} diff --git a/src/ranges.rs b/src/ranges.rs index e9fc8e2..584884e 100644 --- a/src/ranges.rs +++ b/src/ranges.rs @@ -198,7 +198,7 @@ pub fn assigned_in(e: &Expr, out: &mut HashSet) { assigned_in(v, out); } } - ExprKind::SetField(a, _, b) => { + ExprKind::SetField(a, _, b) | ExprKind::ArrayGuard(a, b) => { assigned_in(a, out); assigned_in(b, out); } diff --git a/tests/run.rs b/tests/run.rs index b4300a2..00b4862 100644 --- a/tests/run.rs +++ b/tests/run.rs @@ -49,6 +49,58 @@ fn run_programs() { assert!(failures.is_empty(), "{}", failures.join("\n\n")); } +#[test] +fn tape_preserves_array_read_effects() { + let dir = std::env::temp_dir().join(format!("puddi-tape-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let src = dir.join("tape.pud"); + std::fs::write(&src, r#" +fn observe_list(xs: List) -> List { + print("list") + xs +} + +fn observe_index(i: Int) -> Int { + print("index {i}") + i +} + +fn main() { + let seed = 123456789 + let relay = seed + let _dead = relay + let index = 1 + let forwarded = index + let values: List = [3, 4] + let kept = values[forwarded] + print("value {kept}") + let _unused_list = observe_list(values)[observe_index(forwarded)] + let empty = __array_new(0) + let _unused_raw = __array_get(empty, observe_index(-1)) + print("after trap") +} +"#).unwrap(); + let build = pud().env("PUD_HOST", "node").env_remove("PUD_NO_OPT") + .args(["build", "--emit-wat", "-o"]).arg(&dir).arg(&src).output().unwrap(); + assert!(build.status.success(), "{}", String::from_utf8_lossy(&build.stderr)); + let wat = std::fs::read_to_string(dir.join("tape.wat")).unwrap(); + let result = Command::new("node").arg(dir.join("puddi.mjs")).arg("run").arg(dir.join("tape.wasm")).output().unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + + assert!(!wat.contains("i32.const 123456789"), "the dead binding chain survived"); + let guards: Vec<_> = wat.match_indices("array.len i32.ge_u if\n").collect(); + assert_eq!(guards.len(), 2, "the list and raw read should both have an explicit guard"); + for (offset, guard) in guards { + let mut failure_path = wat[offset + guard.len()..].lines(); + assert!(failure_path.next().unwrap().contains("array.get_u")); + assert_eq!(failure_path.next().unwrap().trim(), "end i32.const 0"); + } + assert_eq!(String::from_utf8_lossy(&result.stdout).lines().collect::>(), ["value 4", "list", "index 1", "index -1"]); + let stderr = String::from_utf8_lossy(&result.stderr); + assert_eq!(result.status.code(), Some(101), "{stderr}"); + assert_eq!(stderr.trim(), "panic: index out of bounds"); +} + #[test] fn reject_programs() { let mut failures = Vec::new();