Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
32 changes: 32 additions & 0 deletions docs/tape.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
2 changes: 1 addition & 1 deletion src/elab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
2 changes: 2 additions & 0 deletions src/ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ pub enum ExprKind {
SetLocal(LocalId, Box<Expr>),
Call(FnInst, Vec<Expr>),
Intrinsic(String, Vec<Ty>, Vec<Expr>),
/// Check a scalar array read without fetching its element. Produces unit.
ArrayGuard(Box<Expr>, Box<Expr>),
CallIndirect(Box<Expr>, Vec<Expr>),
FnValue(FnInst),
Closure { func: usize, captures: Vec<LocalId> },
Expand Down
42 changes: 12 additions & 30 deletions src/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -97,11 +99,13 @@ fn optimize(funcs: &[Option<Func>], insts: &HashMap<FnInst, usize>, 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;
Expand Down Expand Up @@ -555,38 +559,16 @@ 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),
_ => false,
}
}

/// 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)) {
Expand All @@ -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);
}
Expand Down Expand Up @@ -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);
}
Expand Down
Loading
Loading