| @@ -0,0 +1,1323 @@ |
| 1 | +//! The simplifier (issue #196, ADR 0043): inlining, beta reduction, |
| 2 | +//! case-of-known-constructor, dead-let elimination, let sinking and copy |
| 3 | +//! propagation, per function, to a fixed point with a budget. |
| 4 | +//! |
| 5 | +//! It runs before TRMC and Perceus, so it never sees `CtxExtend`, |
| 6 | +//! `CtxApply`, `Dup`, `Drop`, `Release` or `Reuse`: those passes' |
| 7 | +//! invariants are unaffected. Only pure values — atoms, projections, |
| 8 | +//! primitives, constructions, tuples and closures, which no run of the |
| 9 | +//! program can observe — are removed or moved, and they never cross a |
| 10 | +//! call, a `perform` or a `handle`: effects keep their order, and the |
| 11 | +//! yield checks the C backend inserts later come after that order is |
| 12 | +//! fixed. Tail calls stay tail calls (ADR 0003): a call in tail position |
| 13 | +//! is inlined with its body's returns (and `exit`s) in place, and no |
| 14 | +//! other call gains a continuation. |
| 15 | +//! |
| 16 | +//! Variables are unique within a function (Core is in A-normal form with |
| 17 | +//! fresh names), so what is known about a variable holds wherever it is |
| 18 | +//! in scope, and one map serves every branch. |
| 19 | + |
| 20 | +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; |
| 21 | +use std::rc::Rc; |
| 22 | + |
| 23 | +use crate::ir::{Atom, Expr, FnDecl, FnId, Program, Span, Value, VarId}; |
| 24 | + |
| 25 | +/// A function of at most this many nodes is inlinable at any site. (The |
| 26 | +/// `std/iter` combinators measure 15–30: the point of them is that they |
| 27 | +/// dissolve into their caller, issue #199.) |
| 28 | +const SMALL_NODES: u32 = 32; |
| 29 | +/// A bigger non-recursive function is inlinable only where its result is |
| 30 | +/// the caller's (a tail site): nothing after the call is duplicated then. |
| 31 | +const TAIL_NODES: u32 = 64; |
| 32 | +/// Rounds of rewriting: the fixed point of the rewrites, capped (one |
| 33 | +/// round can expose another — a known constructor behind an inlined call, |
| 34 | +/// say). |
| 35 | +const MAX_ROUNDS: u32 = 4; |
| 36 | +/// Inlining into a function stops when it passes this many nodes, or this |
| 37 | +/// factor times where it started, whichever is larger: growth is bounded. |
| 38 | +const MAX_NODES: u32 = 512; |
| 39 | +const MAX_GROWTH: u32 = 4; |
| 40 | + |
| 41 | +/// Simplify the functions `live` of `program`, to the fixed point. |
| 42 | +pub fn run_in(program: &mut Program, live: &[FnId]) { |
| 43 | + // Growth is bounded over the whole pass, not per round: two functions |
| 44 | + // inlining into each other would otherwise grow on every round. |
| 45 | + let mut grown = vec![0u32; program.fns.len()]; |
| 46 | + let mut caps = vec![0u32; program.fns.len()]; |
| 47 | + for _ in 0..MAX_ROUNDS { |
| 48 | + let candidates = candidates(program); |
| 49 | + let mut changed = false; |
| 50 | + for &id in live { |
| 51 | + if caps[id as usize] == 0 { |
| 52 | + let size = size(&program.fns[id as usize].body); |
| 53 | + caps[id as usize] = MAX_NODES.max(MAX_GROWTH * size); |
| 54 | + } |
| 55 | + changed |= function( |
| 56 | + program, |
| 57 | + id, |
| 58 | + &candidates, |
| 59 | + &mut grown[id as usize], |
| 60 | + caps[id as usize], |
| 61 | + ); |
| 62 | + } |
| 63 | + if !changed { |
| 64 | + return; |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +/// Simplify one function; whether anything was rewritten. |
| 70 | +fn function( |
| 71 | + program: &mut Program, |
| 72 | + id: FnId, |
| 73 | + candidates: &HashMap<FnId, Candidate>, |
| 74 | + grown: &mut u32, |
| 75 | + cap: u32, |
| 76 | +) -> bool { |
| 77 | + let decl = &mut program.fns[id as usize]; |
| 78 | + let body = std::mem::replace(&mut decl.body, Expr::Return(Atom::Unit)); |
| 79 | + let mut s = Simplify { |
| 80 | + candidates, |
| 81 | + module: decl.module.as_deref().map(Rc::from), |
| 82 | + subst: HashMap::new(), |
| 83 | + known: HashMap::new(), |
| 84 | + switch_blocks: HashMap::new(), |
| 85 | + dead: HashSet::new(), |
| 86 | + next_var: decl.n_vars, |
| 87 | + shapes: std::mem::take(&mut decl.shapes), |
| 88 | + inlined: HashSet::from([id]), |
| 89 | + grown, |
| 90 | + cap, |
| 91 | + changed: false, |
| 92 | + }; |
| 93 | + let uses = uses(&body); |
| 94 | + let body = s.expr(body, &uses, true); |
| 95 | + let body = sweep(body, &mut s.changed); |
| 96 | + let changed = s.changed; |
| 97 | + let decl = &mut program.fns[id as usize]; |
| 98 | + decl.body = body; |
| 99 | + decl.n_vars = s.next_var; |
| 100 | + decl.shapes = s.shapes; |
| 101 | + if changed { |
| 102 | + let mut present = HashSet::new(); |
| 103 | + visit(&decl.body, &mut |a| { |
| 104 | + if let Atom::Var(v) = a { |
| 105 | + present.insert(*v); |
| 106 | + } |
| 107 | + }); |
| 108 | + decl.shapes.retain(|v, _| present.contains(v)); |
| 109 | + } |
| 110 | + changed |
| 111 | +} |
| 112 | + |
| 113 | +/// What is known at compile time about a variable's value. |
| 114 | +#[derive(Clone, Debug)] |
| 115 | +enum Known { |
| 116 | + /// A closure of this function with these captures. |
| 117 | + Closure(FnId, Vec<Atom>), |
| 118 | + /// A constructor's tag and fields. |
| 119 | + Construct(u32, Vec<Atom>), |
| 120 | + /// A tuple's fields. |
| 121 | + Tuple(Vec<Atom>), |
| 122 | +} |
| 123 | + |
| 124 | +/// How a function body's value reaches its caller. |
| 125 | +#[derive(Clone, Copy, PartialEq, Eq)] |
| 126 | +enum End { |
| 127 | + /// A chain of `let`s ending in a return. |
| 128 | + Return, |
| 129 | + /// A chain of `let`s ending in a panic: what followed the call is |
| 130 | + /// dead, so the body may replace it. |
| 131 | + Panic, |
| 132 | + /// Anything else (a switch, or an `exit` anywhere): inlining one at a |
| 133 | + /// non-tail site would duplicate the continuation or leave the wrong |
| 134 | + /// function. |
| 135 | + Other, |
| 136 | +} |
| 137 | + |
| 138 | +/// A function another may inline (any non-recursive one). |
| 139 | +#[derive(Clone)] |
| 140 | +struct Candidate { |
| 141 | + params: Vec<VarId>, |
| 142 | + body: Rc<Expr>, |
| 143 | + n_vars: u32, |
| 144 | + shapes: Rc<BTreeMap<VarId, Vec<u32>>>, |
| 145 | + /// The callee's module (its C unit, ADR 0029): inlining across named |
| 146 | + /// modules would make a unit's C depend on another module's body, and |
| 147 | + /// an edit there would recompile it. A caller without a module — |
| 148 | + /// generated code, a specialiser's copy — may inline anything: its |
| 149 | + /// `+specialised` unit is cross-cutting already. And a callee in std |
| 150 | + /// may be inlined anywhere: std ships with the toolchain, so its |
| 151 | + /// units' stability is the toolchain's own (and `std/iter`'s stream |
| 152 | + /// fusion, issue #199, needs it). Other cross-module calls are |
| 153 | + /// specialisation's business (issue #197); its copies are generated |
| 154 | + /// too. |
| 155 | + module: Option<Rc<str>>, |
| 156 | + nodes: u32, |
| 157 | + end: End, |
| 158 | + has_exit: bool, |
| 159 | +} |
| 160 | + |
| 161 | +fn candidates(program: &Program) -> HashMap<FnId, Candidate> { |
| 162 | + program |
| 163 | + .fns |
| 164 | + .iter() |
| 165 | + .enumerate() |
| 166 | + .filter(|(id, f)| !recursive(&f.body, *id as FnId) && !is_constant_dictionary(f)) |
| 167 | + .map(|(id, f)| { |
| 168 | + ( |
| 169 | + id as FnId, |
| 170 | + Candidate { |
| 171 | + params: f.params.clone(), |
| 172 | + body: Rc::new(f.body.clone()), |
| 173 | + n_vars: f.n_vars, |
| 174 | + shapes: Rc::new(f.shapes.clone()), |
| 175 | + module: f.module.as_deref().map(Rc::from), |
| 176 | + nodes: size(&f.body), |
| 177 | + end: end_of(&f.body), |
| 178 | + has_exit: has_exit(&f.body), |
| 179 | + }, |
| 180 | + ) |
| 181 | + }) |
| 182 | + .collect() |
| 183 | +} |
| 184 | + |
| 185 | +/// Whether `f` is a constant dictionary (ADR 0007): a nullary function |
| 186 | +/// whose body is no-capture closures and then a tuple of them. The C |
| 187 | +/// backend folds one to an immortal static (see `constant` in |
| 188 | +/// `louise_codegen_c`), so a call to it is a reference; inlining would |
| 189 | +/// instead rebuild the closures and the tuple at every call site — a |
| 190 | +/// 27× regression on a generic call in a loop (issue #195's review). |
| 191 | +fn is_constant_dictionary(f: &FnDecl) -> bool { |
| 192 | + if !f.params.is_empty() { |
| 193 | + return false; |
| 194 | + } |
| 195 | + let mut e = &f.body; |
| 196 | + loop { |
| 197 | + match e { |
| 198 | + Expr::Let(_, value, rest, _) => { |
| 199 | + match &**value { |
| 200 | + Value::Closure(_, caps) if caps.is_empty() => {} |
| 201 | + Value::Tuple(args) if !args.is_empty() => {} |
| 202 | + _ => return false, |
| 203 | + } |
| 204 | + e = rest; |
| 205 | + } |
| 206 | + Expr::Return(Atom::Var(_)) => return true, |
| 207 | + _ => return false, |
| 208 | + } |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +struct Simplify<'a> { |
| 213 | + candidates: &'a HashMap<FnId, Candidate>, |
| 214 | + /// The function's own module: only same-module callees are inlined |
| 215 | + /// (Candidate::module). |
| 216 | + module: Option<Rc<str>>, |
| 217 | + /// Variables bound to atoms, to substitute (copy propagation). |
| 218 | + subst: HashMap<VarId, Atom>, |
| 219 | + known: HashMap<VarId, Known>, |
| 220 | + /// Variables bound to a block that ends in a switch (`let v = { |
| 221 | + /// switch … }`): for case-of-case — a switch on `v` moves into the |
| 222 | + /// inner arms, where the constructor each arm builds is known. |
| 223 | + switch_blocks: HashMap<VarId, Rc<Expr>>, |
| 224 | + /// `let`s a rewrite consumed (a switch block folded into its user): |
| 225 | + /// dropped when the chain is rebuilt. |
| 226 | + dead: HashSet<VarId>, |
| 227 | + /// Fresh variables: the function's `n_vars`, growing as inlining |
| 228 | + /// brings a callee's variables in. |
| 229 | + next_var: u32, |
| 230 | + /// The function's `shapes` (ADR 0040), rewritten with it. |
| 231 | + shapes: BTreeMap<VarId, Vec<u32>>, |
| 232 | + /// The function itself and the functions already inlined at an |
| 233 | + /// enclosing point of this walk: never inlined again within it, so |
| 234 | + /// mutually recursive pairs terminate. |
| 235 | + inlined: HashSet<FnId>, |
| 236 | + /// Nodes inlined so far (over the whole pass), and the cap. |
| 237 | + grown: &'a mut u32, |
| 238 | + cap: u32, |
| 239 | + changed: bool, |
| 240 | +} |
| 241 | + |
| 242 | +impl Simplify<'_> { |
| 243 | + fn atom(&self, a: &Atom) -> Atom { |
| 244 | + match a { |
| 245 | + Atom::Var(v) => self.subst.get(v).cloned().unwrap_or_else(|| a.clone()), |
| 246 | + a => a.clone(), |
| 247 | + } |
| 248 | + } |
| 249 | + |
| 250 | + fn atoms(&self, atoms: &[Atom]) -> Vec<Atom> { |
| 251 | + atoms.iter().map(|a| self.atom(a)).collect() |
| 252 | + } |
| 253 | + |
| 254 | + /// A chain of `let`s and its end. `exits_ok` is whether the chain is |
| 255 | + /// the function's own (not a block's): an inlined `exit` leaves the |
| 256 | + /// function, so only there is a body's `exit` the caller's (a |
| 257 | + /// `Return` is the enclosing block's value, ir.rs). |
| 258 | + fn expr(&mut self, e: Expr, uses: &HashMap<VarId, u32>, exits_ok: bool) -> Expr { |
| 259 | + let (lets, end) = split(e); |
| 260 | + let mut lets: VecDeque<(VarId, Value, Option<Span>)> = lets.into_iter().collect(); |
| 261 | + let mut end = end; |
| 262 | + let mut out: Vec<(VarId, Value, Option<Span>)> = Vec::new(); |
| 263 | + while let Some((v, value, span)) = lets.pop_front() { |
| 264 | + // A block that is a plain `let`-chain is structural nesting: |
| 265 | + // splice it (a block ending in a switch yields its value |
| 266 | + // through the branches' returns, so only chain ends flatten). |
| 267 | + if let Value::Block(b) = &value { |
| 268 | + let (blets, bend) = split((**b).clone()); |
| 269 | + if let Expr::Return(a) = bend { |
| 270 | + let mut pasted = blets; |
| 271 | + pasted.push((v, Value::Atom(a), span)); |
| 272 | + for item in pasted.into_iter().rev() { |
| 273 | + lets.push_front(item); |
| 274 | + } |
| 275 | + self.changed = true; |
| 276 | + continue; |
| 277 | + } |
| 278 | + } |
| 279 | + let mut value = self.value(value, uses); |
| 280 | + // Beta reduction: a call of a known closure becomes a direct |
| 281 | + // call (its captures come first, ir.rs's convention). |
| 282 | + let mut force = false; |
| 283 | + if let Value::Call(Atom::Var(f), args) = &value |
| 284 | + && let Some(Known::Closure(g, caps)) = self.known.get(f).cloned() |
| 285 | + { |
| 286 | + // A closure used exactly once: its function's size no |
| 287 | + // longer matters, inlining moves code instead of copying |
| 288 | + // it. |
| 289 | + force = uses.get(f) == Some(&1); |
| 290 | + let mut all = caps; |
| 291 | + all.extend(args.iter().cloned()); |
| 292 | + value = Value::CallFn(g, all); |
| 293 | + self.changed = true; |
| 294 | + } |
| 295 | + // Inlining. |
| 296 | + if let Value::CallFn(g, args) = &value |
| 297 | + && !self.inlined.contains(g) |
| 298 | + && let Some(cand) = self.candidates.get(g).cloned() |
| 299 | + && (self.module.is_none() |
| 300 | + || cand.module == self.module |
| 301 | + || cand |
| 302 | + .module |
| 303 | + .as_deref() |
| 304 | + .is_some_and(|m| m.starts_with("std/"))) |
| 305 | + && cand.params.len() == args.len() |
| 306 | + { |
| 307 | + let tail_site = |
| 308 | + lets.is_empty() && matches!(&end, Expr::Return(Atom::Var(r)) if *r == v); |
| 309 | + let within = *self.grown + cand.nodes <= self.cap; |
| 310 | + let chain = matches!(cand.end, End::Return | End::Panic) && !cand.has_exit; |
| 311 | + let tail = tail_site |
| 312 | + && (exits_ok || !cand.has_exit) |
| 313 | + && (force || cand.nodes <= TAIL_NODES && within); |
| 314 | + let ok = if force { |
| 315 | + // Used exactly once, inlining moves code instead of |
| 316 | + // copying it: only the shape matters. |
| 317 | + chain || tail |
| 318 | + } else { |
| 319 | + (chain && cand.nodes <= SMALL_NODES && within) || tail |
| 320 | + }; |
| 321 | + if ok { |
| 322 | + *self.grown += cand.nodes; |
| 323 | + self.inlined.insert(*g); |
| 324 | + let (mut pasted, pend) = self.inline(&cand, args); |
| 325 | + self.inlined.remove(g); |
| 326 | + match pend { |
| 327 | + Expr::Return(a) => { |
| 328 | + pasted.push((v, Value::Atom(a), span)); |
| 329 | + for item in pasted.into_iter().rev() { |
| 330 | + lets.push_front(item); |
| 331 | + } |
| 332 | + } |
| 333 | + // A panic makes the rest dead; at a tail site the |
| 334 | + // rest was `return v`, which the body replaces. |
| 335 | + pend => { |
| 336 | + lets = pasted.into_iter().collect(); |
| 337 | + end = pend; |
| 338 | + } |
| 339 | + } |
| 340 | + self.changed = true; |
| 341 | + continue; |
| 342 | + } |
| 343 | + } |
| 344 | + // Copy propagation, and what is known about the value. |
| 345 | + match &value { |
| 346 | + Value::Atom(a) => { |
| 347 | + if let (Atom::Var(u), Some(shapes)) = (a, self.shapes.remove(&v)) { |
| 348 | + self.shapes.entry(*u).or_insert(shapes); |
| 349 | + } |
| 350 | + self.subst.insert(v, a.clone()); |
| 351 | + self.changed = true; |
| 352 | + continue; |
| 353 | + } |
| 354 | + Value::Closure(g, caps) => { |
| 355 | + self.known.insert(v, Known::Closure(*g, caps.clone())); |
| 356 | + } |
| 357 | + Value::Construct { tag, args, .. } => { |
| 358 | + self.known.insert(v, Known::Construct(*tag, args.clone())); |
| 359 | + } |
| 360 | + Value::Tuple(args) => { |
| 361 | + self.known.insert(v, Known::Tuple(args.clone())); |
| 362 | + } |
| 363 | + _ => { |
| 364 | + self.known.remove(&v); |
| 365 | + } |
| 366 | + } |
| 367 | + out.push((v, value, span)); |
| 368 | + // A block ending in a switch, used once as a later switch's |
| 369 | + // scrutinee, is a case-of-case candidate. |
| 370 | + if let Value::Block(b) = &out.last().expect("just pushed").1 |
| 371 | + && ends_in_switch(b) |
| 372 | + { |
| 373 | + self.switch_blocks.insert(v, Rc::new((**b).clone())); |
| 374 | + } |
| 375 | + } |
| 376 | + let end = self.end(end, uses, exits_ok); |
| 377 | + let mut expr = end; |
| 378 | + for (v, value, span) in out.into_iter().rev() { |
| 379 | + if self.dead.contains(&v) { |
| 380 | + continue; |
| 381 | + } |
| 382 | + expr = Expr::Let(v, Box::new(value), Box::new(expr), span); |
| 383 | + } |
| 384 | + expr |
| 385 | + } |
| 386 | + |
| 387 | + /// The candidate's body renamed into this function (its parameters to |
| 388 | + /// the arguments, its other variables fresh), split into its `let`s |
| 389 | + /// and its end. |
| 390 | + fn inline( |
| 391 | + &mut self, |
| 392 | + cand: &Candidate, |
| 393 | + args: &[Atom], |
| 394 | + ) -> (Vec<(VarId, Value, Option<Span>)>, Expr) { |
| 395 | + let mut map: Vec<Option<Atom>> = vec![None; cand.n_vars as usize]; |
| 396 | + for (p, a) in cand.params.iter().zip(args) { |
| 397 | + map[*p as usize] = Some(a.clone()); |
| 398 | + } |
| 399 | + let mut next = self.next_var; |
| 400 | + for w in 0..cand.n_vars { |
| 401 | + if map[w as usize].is_none() { |
| 402 | + map[w as usize] = Some(Atom::Var(next)); |
| 403 | + next += 1; |
| 404 | + } |
| 405 | + } |
| 406 | + self.next_var = next; |
| 407 | + for (w, arities) in cand.shapes.iter() { |
| 408 | + if let Some(Atom::Var(u)) = &map[*w as usize] { |
| 409 | + self.shapes.entry(*u).or_insert_with(|| arities.clone()); |
| 410 | + } |
| 411 | + } |
| 412 | + let renamed = rename(&cand.body, &mut |w| { |
| 413 | + map[w as usize].clone().expect("every variable is mapped") |
| 414 | + }); |
| 415 | + split(renamed) |
| 416 | + } |
| 417 | + |
| 418 | + /// A chain's end: copy propagation, case-of-known-constructor, and |
| 419 | + /// the same treatment for the branches (which keep the chain's |
| 420 | + /// level: a top-level switch's branches are top-level too). |
| 421 | + fn end(&mut self, e: Expr, uses: &HashMap<VarId, u32>, exits_ok: bool) -> Expr { |
| 422 | + match e { |
| 423 | + Expr::Switch { on, cases, default } => { |
| 424 | + let on = self.atom(&on); |
| 425 | + let tag = match &on { |
| 426 | + Atom::Var(x) => match self.known.get(x) { |
| 427 | + Some(Known::Construct(tag, _)) => Some(*tag), |
| 428 | + _ => None, |
| 429 | + }, |
| 430 | + _ => None, |
| 431 | + }; |
| 432 | + if let Some(tag) = tag { |
| 433 | + let branch = cases |
| 434 | + .iter() |
| 435 | + .find(|(t, _)| *t == tag) |
| 436 | + .map(|(_, b)| b) |
| 437 | + .or(default.as_deref()); |
| 438 | + if let Some(branch) = branch { |
| 439 | + self.changed = true; |
| 440 | + return self.expr(branch.clone(), uses, exits_ok); |
| 441 | + } |
| 442 | + } |
| 443 | + // Case-of-case: a switch on a value a block computed by a |
| 444 | + // switch. The outer switch moves into the inner arms, |
| 445 | + // where the constructor each arm builds is known — this |
| 446 | + // is what dissolves a stream-fusion pipeline's per-pull |
| 447 | + // `Step` (issue #199). Only when the inner block is free |
| 448 | + // of effects and panics (its `let`s move position) and |
| 449 | + // `v` is used once. |
| 450 | + if let Atom::Var(x) = &on { |
| 451 | + // `x` may be used again by the arms' field |
| 452 | + // projections of it: the gate is "no use outside this |
| 453 | + // switch", so count the scrutinee and the arms. |
| 454 | + let mut inside = 1u32; |
| 455 | + for b in cases |
| 456 | + .iter() |
| 457 | + .map(|(_, b)| b) |
| 458 | + .chain(default.iter().map(|d| &**d)) |
| 459 | + { |
| 460 | + visit(b, &mut |a| { |
| 461 | + if *a == Atom::Var(*x) { |
| 462 | + inside += 1; |
| 463 | + } |
| 464 | + }); |
| 465 | + } |
| 466 | + // The arms are raw (the chain walk substituted only |
| 467 | + // `on`): normalise them through the substitution map |
| 468 | + // first, so their scrutinee references are the same |
| 469 | + // variable as `x` (aliases of it become it). |
| 470 | + let subst = self.subst.clone(); |
| 471 | + let norm = |b: &Expr| { |
| 472 | + rename(b, &mut |w| subst.get(&w).cloned().unwrap_or(Atom::Var(w))) |
| 473 | + }; |
| 474 | + let norm_cases: Vec<(u32, Expr)> = |
| 475 | + cases.iter().map(|(t, b)| (*t, norm(b))).collect(); |
| 476 | + let norm_default = default.as_deref().map(norm); |
| 477 | + if uses.get(x) == Some(&inside) |
| 478 | + && let Some(inner) = self.switch_blocks.get(x).cloned() |
| 479 | + && block_pure(&inner) |
| 480 | + && let Some(lifted) = |
| 481 | + self.case_of_case(&inner, *x, &norm_cases, norm_default.as_ref()) |
| 482 | + { |
| 483 | + self.dead.insert(*x); |
| 484 | + self.changed = true; |
| 485 | + return self.expr(lifted, uses, exits_ok); |
| 486 | + } |
| 487 | + } |
| 488 | + Expr::Switch { |
| 489 | + on, |
| 490 | + cases: cases |
| 491 | + .into_iter() |
| 492 | + .map(|(t, b)| (t, self.expr(b, uses, exits_ok))) |
| 493 | + .collect(), |
| 494 | + default: default.map(|d| Box::new(self.expr(*d, uses, exits_ok))), |
| 495 | + } |
| 496 | + } |
| 497 | + Expr::SwitchLit { on, cases, default } => { |
| 498 | + let on = self.atom(&on); |
| 499 | + if let Atom::Lit(l) = &on { |
| 500 | + let branch = cases |
| 501 | + .iter() |
| 502 | + .find(|(c, _)| c == l) |
| 503 | + .map(|(_, b)| b) |
| 504 | + .unwrap_or(&default); |
| 505 | + self.changed = true; |
| 506 | + return self.expr(branch.clone(), uses, exits_ok); |
| 507 | + } |
| 508 | + Expr::SwitchLit { |
| 509 | + on, |
| 510 | + cases: cases |
| 511 | + .into_iter() |
| 512 | + .map(|(c, b)| (c, self.expr(b, uses, exits_ok))) |
| 513 | + .collect(), |
| 514 | + default: Box::new(self.expr(*default, uses, exits_ok)), |
| 515 | + } |
| 516 | + } |
| 517 | + Expr::Return(a) => Expr::Return(self.atom(&a)), |
| 518 | + Expr::Exit(a) => Expr::Exit(self.atom(&a)), |
| 519 | + Expr::Panic(p) => Expr::Panic(p), |
| 520 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 521 | + unreachable!("Core before Perceus") |
| 522 | + } |
| 523 | + Expr::ReturnN(_) | Expr::LetN(..) => unreachable!("Core before the CPR pass"), |
| 524 | + Expr::Let(..) => unreachable!("a chain's end is never a `let`"), |
| 525 | + } |
| 526 | + } |
| 527 | + |
| 528 | + /// Case-of-case: `inner` is `v`'s block, a chain ending in a switch; |
| 529 | + /// the outer switch (`cases`, `default`) moves into each inner arm, |
| 530 | + /// where what the arm built is known to the constructor fold. None if |
| 531 | + /// any arm can't take it, or if the growth is over budget. |
| 532 | + fn case_of_case( |
| 533 | + &mut self, |
| 534 | + inner: &Expr, |
| 535 | + scrutinee: VarId, |
| 536 | + cases: &[(u32, Expr)], |
| 537 | + default: Option<&Expr>, |
| 538 | + ) -> Option<Expr> { |
| 539 | + let (lets, end) = split(inner.clone()); |
| 540 | + let Expr::Switch { |
| 541 | + on, |
| 542 | + cases: inner_cases, |
| 543 | + default: inner_default, |
| 544 | + } = end |
| 545 | + else { |
| 546 | + return None; |
| 547 | + }; |
| 548 | + // The outer switch is cloned into each inner arm: bounded by the |
| 549 | + // function's growth budget, as inlining's. |
| 550 | + let outer_size: u32 = cases.iter().map(|(_, b)| size(b)).sum::<u32>() |
| 551 | + + default.as_ref().map_or(0, |d| size(d)); |
| 552 | + let arms = inner_cases.len() as u32 + inner_default.is_some() as u32; |
| 553 | + let growth = outer_size.saturating_mul(arms); |
| 554 | + if *self.grown + growth > self.cap { |
| 555 | + return None; |
| 556 | + } |
| 557 | + *self.grown += growth; |
| 558 | + // Variables bound by the outer arms are freshened per inner arm |
| 559 | + // (variables are unique within a function), and the scrutinee is |
| 560 | + // the arm's result there. |
| 561 | + let mut bound = BTreeSet::new(); |
| 562 | + for (_, b) in cases { |
| 563 | + collect_bound(b, &mut bound); |
| 564 | + } |
| 565 | + if let Some(d) = default { |
| 566 | + collect_bound(d, &mut bound); |
| 567 | + } |
| 568 | + let mut arms = Vec::new(); |
| 569 | + for (t, body) in inner_cases { |
| 570 | + arms.push(( |
| 571 | + t, |
| 572 | + self.append_switch(body, scrutinee, cases, default, &bound)?, |
| 573 | + )); |
| 574 | + } |
| 575 | + let new_default = match inner_default { |
| 576 | + Some(d) => Some(Box::new( |
| 577 | + self.append_switch(*d, scrutinee, cases, default, &bound)?, |
| 578 | + )), |
| 579 | + None => None, |
| 580 | + }; |
| 581 | + Some(rebuild( |
| 582 | + lets, |
| 583 | + Expr::Switch { |
| 584 | + on, |
| 585 | + cases: arms, |
| 586 | + default: new_default, |
| 587 | + }, |
| 588 | + )) |
| 589 | + } |
| 590 | + |
| 591 | + /// `body` with the outer switch appended after its result. The arm's |
| 592 | + /// result is the scrutinee there (and what it built is known to the |
| 593 | + /// constructor fold). A panic or an `exit` ends the arm — the outer |
| 594 | + /// switch is never reached. |
| 595 | + fn append_switch( |
| 596 | + &mut self, |
| 597 | + body: Expr, |
| 598 | + scrutinee: VarId, |
| 599 | + cases: &[(u32, Expr)], |
| 600 | + default: Option<&Expr>, |
| 601 | + bound: &BTreeSet<VarId>, |
| 602 | + ) -> Option<Expr> { |
| 603 | + let (lets, end) = split(body); |
| 604 | + let end = match end { |
| 605 | + Expr::Return(a @ Atom::Var(_)) => { |
| 606 | + // Rebind the scrutinee to a *fresh* variable holding the |
| 607 | + // arm's result (the scrutinee's own `let` is consumed by |
| 608 | + // the lift), then the outer switch: its arms keep |
| 609 | + // working, and copy propagation and the constructor fold |
| 610 | + // take it from there. |
| 611 | + let mut freshen: HashMap<VarId, VarId> = |
| 612 | + bound.iter().map(|w| (*w, self.fresh_var())).collect(); |
| 613 | + let s = self.fresh_var(); |
| 614 | + freshen.insert(scrutinee, s); |
| 615 | + let m = &mut |w: VarId| match freshen.get(&w) { |
| 616 | + Some(f) => Atom::Var(*f), |
| 617 | + None => Atom::Var(w), |
| 618 | + }; |
| 619 | + let sw = Expr::Switch { |
| 620 | + on: Atom::Var(s), |
| 621 | + cases: cases.iter().map(|(t, b)| (*t, rename(b, m))).collect(), |
| 622 | + default: default.map(|d| Box::new(rename(d, m))), |
| 623 | + }; |
| 624 | + return Some(rebuild( |
| 625 | + lets, |
| 626 | + Expr::Let(s, Box::new(Value::Atom(a)), Box::new(sw), None), |
| 627 | + )); |
| 628 | + } |
| 629 | + end @ (Expr::Panic(_) | Expr::Exit(_)) => end, |
| 630 | + Expr::Switch { |
| 631 | + on, |
| 632 | + cases: inner_cases, |
| 633 | + default: inner_default, |
| 634 | + } => { |
| 635 | + let mut new_cases = Vec::new(); |
| 636 | + for (t, b) in inner_cases { |
| 637 | + new_cases.push((t, self.append_switch(b, scrutinee, cases, default, bound)?)); |
| 638 | + } |
| 639 | + let new_default = match inner_default { |
| 640 | + Some(d) => Some(Box::new( |
| 641 | + self.append_switch(*d, scrutinee, cases, default, bound)?, |
| 642 | + )), |
| 643 | + None => None, |
| 644 | + }; |
| 645 | + Expr::Switch { |
| 646 | + on, |
| 647 | + cases: new_cases, |
| 648 | + default: new_default, |
| 649 | + } |
| 650 | + } |
| 651 | + Expr::Return(_) => return None, // a literal: not a tag switch |
| 652 | + Expr::SwitchLit { .. } => return None, // literals: not a tag switch |
| 653 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 654 | + unreachable!("Core before Perceus") |
| 655 | + } |
| 656 | + Expr::ReturnN(_) | Expr::LetN(..) => unreachable!("Core before the CPR pass"), |
| 657 | + Expr::Let(..) => unreachable!("a chain's end is never a `let`"), |
| 658 | + }; |
| 659 | + Some(rebuild(lets, end)) |
| 660 | + } |
| 661 | + |
| 662 | + /// A fresh variable for the enclosing function. |
| 663 | + fn fresh_var(&mut self) -> VarId { |
| 664 | + let v = self.next_var; |
| 665 | + self.next_var += 1; |
| 666 | + v |
| 667 | + } |
| 668 | + |
| 669 | + fn value(&mut self, value: Value, uses: &HashMap<VarId, u32>) -> Value { |
| 670 | + match value { |
| 671 | + Value::Atom(a) => Value::Atom(self.atom(&a)), |
| 672 | + Value::Call(f, args) => Value::Call(self.atom(&f), self.atoms(&args)), |
| 673 | + Value::CallFn(g, args) => Value::CallFn(g, self.atoms(&args)), |
| 674 | + Value::CallExtern(s, args) => Value::CallExtern(s, self.atoms(&args)), |
| 675 | + Value::Prim(p, args) => Value::Prim(p, self.atoms(&args)), |
| 676 | + Value::Construct { tag, name, args } => Value::Construct { |
| 677 | + tag, |
| 678 | + name, |
| 679 | + args: self.atoms(&args), |
| 680 | + }, |
| 681 | + Value::Tuple(args) => Value::Tuple(self.atoms(&args)), |
| 682 | + Value::Field(a, i) => { |
| 683 | + let a = self.atom(&a); |
| 684 | + let folded = match &a { |
| 685 | + Atom::Var(x) => match self.known.get(x) { |
| 686 | + Some(Known::Construct(_, fields)) | Some(Known::Tuple(fields)) => { |
| 687 | + fields.get(i as usize).cloned() |
| 688 | + } |
| 689 | + _ => None, |
| 690 | + }, |
| 691 | + _ => None, |
| 692 | + }; |
| 693 | + match folded { |
| 694 | + Some(field) => { |
| 695 | + self.changed = true; |
| 696 | + Value::Atom(field) |
| 697 | + } |
| 698 | + None => Value::Field(a, i), |
| 699 | + } |
| 700 | + } |
| 701 | + Value::Closure(g, caps) => Value::Closure(g, self.atoms(&caps)), |
| 702 | + Value::Perform { |
| 703 | + cap, |
| 704 | + effect, |
| 705 | + op, |
| 706 | + args, |
| 707 | + } => Value::Perform { |
| 708 | + cap: self.atom(&cap), |
| 709 | + effect, |
| 710 | + op, |
| 711 | + args: self.atoms(&args), |
| 712 | + }, |
| 713 | + Value::Handle { |
| 714 | + effect, |
| 715 | + body, |
| 716 | + ret, |
| 717 | + clauses, |
| 718 | + } => Value::Handle { |
| 719 | + effect, |
| 720 | + body: self.atom(&body), |
| 721 | + ret: ret.map(|r| self.atom(&r)), |
| 722 | + clauses: self.atoms(&clauses), |
| 723 | + }, |
| 724 | + Value::Region { effects, body } => Value::Region { |
| 725 | + effects, |
| 726 | + body: self.atom(&body), |
| 727 | + }, |
| 728 | + Value::Defer { body, cleanup } => Value::Defer { |
| 729 | + body: self.atom(&body), |
| 730 | + cleanup: self.atom(&cleanup), |
| 731 | + }, |
| 732 | + Value::Block(b) => Value::Block(Box::new(self.expr(*b, uses, false))), |
| 733 | + Value::Reuse { .. } | Value::CtxExtend { .. } | Value::CtxApply { .. } => { |
| 734 | + unreachable!("Core before TRMC and Perceus") |
| 735 | + } |
| 736 | + } |
| 737 | + } |
| 738 | +} |
| 739 | + |
| 740 | +/// Whether removing or moving a `let` of `value` changes nothing but |
| 741 | +/// allocation: no call, operation or control flow. |
| 742 | +fn pure(value: &Value) -> bool { |
| 743 | + matches!( |
| 744 | + value, |
| 745 | + Value::Atom(_) |
| 746 | + | Value::Field(..) |
| 747 | + | Value::Prim(..) |
| 748 | + | Value::Tuple(_) |
| 749 | + | Value::Construct { .. } |
| 750 | + | Value::Closure(..) |
| 751 | + ) |
| 752 | +} |
| 753 | + |
| 754 | +/// `let v = value; rest`, as the chain of its `let`s and the end they |
| 755 | +/// lead to. |
| 756 | +pub(crate) fn split(mut e: Expr) -> (Vec<(VarId, Value, Option<Span>)>, Expr) { |
| 757 | + let mut lets = Vec::new(); |
| 758 | + while let Expr::Let(v, value, rest, span) = e { |
| 759 | + lets.push((v, *value, span)); |
| 760 | + e = *rest; |
| 761 | + } |
| 762 | + (lets, e) |
| 763 | +} |
| 764 | + |
| 765 | +/// Remove `let`s of pure values nothing uses, and sink a pure `let` used |
| 766 | +/// in exactly one branch of the following switch into it: it is computed |
| 767 | +/// only on that path. |
| 768 | +fn sweep(e: Expr, changed: &mut bool) -> Expr { |
| 769 | + sweep_in(e, &mut HashSet::new(), changed) |
| 770 | +} |
| 771 | + |
| 772 | +fn sweep_in(e: Expr, used: &mut HashSet<VarId>, changed: &mut bool) -> Expr { |
| 773 | + let (mut lets, end) = split(e); |
| 774 | + let mut end = match end { |
| 775 | + Expr::Return(a) => { |
| 776 | + var(&a, used); |
| 777 | + Expr::Return(a) |
| 778 | + } |
| 779 | + Expr::Exit(a) => { |
| 780 | + var(&a, used); |
| 781 | + Expr::Exit(a) |
| 782 | + } |
| 783 | + Expr::Panic(p) => Expr::Panic(p), |
| 784 | + Expr::Switch { on, cases, default } => { |
| 785 | + var(&on, used); |
| 786 | + let (tags, mut bodies): (Vec<u32>, Vec<Expr>) = cases.into_iter().unzip(); |
| 787 | + let has_default = default.is_some(); |
| 788 | + if let Some(d) = default { |
| 789 | + bodies.push(*d); |
| 790 | + } |
| 791 | + // What a branch uses decides what the chain before the switch |
| 792 | + // must keep, so the branches' own set stays apart: sinking a |
| 793 | + // `let` into one branch must see the uses before the switch, |
| 794 | + // not the branches'. |
| 795 | + let mut inner = HashSet::new(); |
| 796 | + let mut frees = sweep_bodies(&mut bodies, &mut inner, changed); |
| 797 | + sink(&mut lets, &on, &mut bodies, &mut frees, used, changed); |
| 798 | + used.extend(inner); |
| 799 | + let mut bodies = bodies.into_iter(); |
| 800 | + let cases = tags.into_iter().zip(bodies.by_ref()).collect(); |
| 801 | + let default = if has_default { |
| 802 | + Some(Box::new(bodies.next().expect("the default's body"))) |
| 803 | + } else { |
| 804 | + None |
| 805 | + }; |
| 806 | + Expr::Switch { on, cases, default } |
| 807 | + } |
| 808 | + Expr::SwitchLit { on, cases, default } => { |
| 809 | + var(&on, used); |
| 810 | + let (lits, mut bodies): (Vec<crate::ir::Lit>, Vec<Expr>) = cases.into_iter().unzip(); |
| 811 | + bodies.push(*default); |
| 812 | + let mut inner = HashSet::new(); |
| 813 | + let mut frees = sweep_bodies(&mut bodies, &mut inner, changed); |
| 814 | + sink(&mut lets, &on, &mut bodies, &mut frees, used, changed); |
| 815 | + used.extend(inner); |
| 816 | + let mut bodies = bodies.into_iter(); |
| 817 | + let cases = lits.into_iter().zip(bodies.by_ref()).collect(); |
| 818 | + let default = Box::new(bodies.next().expect("the default's body")); |
| 819 | + Expr::SwitchLit { on, cases, default } |
| 820 | + } |
| 821 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 822 | + unreachable!("Core before Perceus") |
| 823 | + } |
| 824 | + Expr::ReturnN(_) | Expr::LetN(..) => unreachable!("Core before the CPR pass"), |
| 825 | + Expr::Let(..) => unreachable!("a chain's end is never a `let`"), |
| 826 | + }; |
| 827 | + while let Some((v, value, span)) = lets.pop() { |
| 828 | + if pure(&value) && !used.contains(&v) { |
| 829 | + *changed = true; |
| 830 | + continue; |
| 831 | + } |
| 832 | + used.remove(&v); |
| 833 | + let value = match value { |
| 834 | + Value::Block(b) => { |
| 835 | + let mut b = sweep_in(*b, &mut HashSet::new(), changed); |
| 836 | + sink_into_block(&mut b, &mut lets, used, changed); |
| 837 | + used.extend(free_vars(&b)); |
| 838 | + Value::Block(Box::new(b)) |
| 839 | + } |
| 840 | + value => { |
| 841 | + value_vars(&value, used); |
| 842 | + value |
| 843 | + } |
| 844 | + }; |
| 845 | + end = Expr::Let(v, Box::new(value), Box::new(end), span); |
| 846 | + } |
| 847 | + end |
| 848 | +} |
| 849 | + |
| 850 | +/// Sweep each branch body; the free variables of each, after. |
| 851 | +fn sweep_bodies( |
| 852 | + bodies: &mut [Expr], |
| 853 | + used: &mut HashSet<VarId>, |
| 854 | + changed: &mut bool, |
| 855 | +) -> Vec<HashSet<VarId>> { |
| 856 | + let mut frees = Vec::with_capacity(bodies.len()); |
| 857 | + for body in bodies { |
| 858 | + *body = sweep_in( |
| 859 | + std::mem::replace(body, Expr::Return(Atom::Unit)), |
| 860 | + used, |
| 861 | + changed, |
| 862 | + ); |
| 863 | + frees.push(free_vars(body)); |
| 864 | + } |
| 865 | + frees |
| 866 | +} |
| 867 | + |
| 868 | +/// Sink the trailing pure `let`s of a chain that end in a switch: a |
| 869 | +/// `let` whose variable is used in exactly one branch (and not after the |
| 870 | +/// switch, nor in the scrutinee) moves into that branch. |
| 871 | +fn sink( |
| 872 | + lets: &mut Vec<(VarId, Value, Option<Span>)>, |
| 873 | + on: &Atom, |
| 874 | + bodies: &mut [Expr], |
| 875 | + frees: &mut [HashSet<VarId>], |
| 876 | + used: &HashSet<VarId>, |
| 877 | + changed: &mut bool, |
| 878 | +) { |
| 879 | + loop { |
| 880 | + let hit = match lets.last() { |
| 881 | + Some((v, value, _)) |
| 882 | + if pure(value) && !used.contains(v) && !matches!(on, Atom::Var(o) if o == v) => |
| 883 | + { |
| 884 | + let mut hits = frees.iter().enumerate().filter(|(_, f)| f.contains(v)); |
| 885 | + match (hits.next(), hits.next()) { |
| 886 | + (Some((i, _)), None) => Some(i), |
| 887 | + _ => None, |
| 888 | + } |
| 889 | + } |
| 890 | + _ => None, |
| 891 | + }; |
| 892 | + let Some(i) = hit else { break }; |
| 893 | + let (v, value, span) = lets.pop().expect("checked above"); |
| 894 | + // The value's own variables are used in that branch now. |
| 895 | + value_vars(&value, &mut frees[i]); |
| 896 | + let body = std::mem::replace(&mut bodies[i], Expr::Return(Atom::Unit)); |
| 897 | + bodies[i] = Expr::Let(v, Box::new(value), Box::new(body), span); |
| 898 | + *changed = true; |
| 899 | + } |
| 900 | +} |
| 901 | + |
| 902 | +/// A block that is exactly a switch takes the pure `let`s before it that |
| 903 | +/// only one branch uses, as a chain ending in the switch would. |
| 904 | +fn sink_into_block( |
| 905 | + b: &mut Expr, |
| 906 | + lets: &mut Vec<(VarId, Value, Option<Span>)>, |
| 907 | + used: &HashSet<VarId>, |
| 908 | + changed: &mut bool, |
| 909 | +) { |
| 910 | + let (prefix, end) = split(std::mem::replace(b, Expr::Return(Atom::Unit))); |
| 911 | + if !prefix.is_empty() { |
| 912 | + *b = rebuild(prefix, end); |
| 913 | + return; |
| 914 | + } |
| 915 | + match end { |
| 916 | + Expr::Switch { on, cases, default } => { |
| 917 | + let (tags, mut bodies): (Vec<u32>, Vec<Expr>) = cases.into_iter().unzip(); |
| 918 | + let has_default = default.is_some(); |
| 919 | + if let Some(d) = default { |
| 920 | + bodies.push(*d); |
| 921 | + } |
| 922 | + let mut frees: Vec<HashSet<VarId>> = bodies.iter().map(free_vars).collect(); |
| 923 | + sink(lets, &on, &mut bodies, &mut frees, used, changed); |
| 924 | + let mut bodies = bodies.into_iter(); |
| 925 | + let cases = tags.into_iter().zip(bodies.by_ref()).collect(); |
| 926 | + let default = if has_default { |
| 927 | + Some(Box::new(bodies.next().expect("the default's body"))) |
| 928 | + } else { |
| 929 | + None |
| 930 | + }; |
| 931 | + *b = Expr::Switch { on, cases, default }; |
| 932 | + } |
| 933 | + Expr::SwitchLit { on, cases, default } => { |
| 934 | + let (lits, mut bodies): (Vec<crate::ir::Lit>, Vec<Expr>) = cases.into_iter().unzip(); |
| 935 | + bodies.push(*default); |
| 936 | + let mut frees: Vec<HashSet<VarId>> = bodies.iter().map(free_vars).collect(); |
| 937 | + sink(lets, &on, &mut bodies, &mut frees, used, changed); |
| 938 | + let mut bodies = bodies.into_iter(); |
| 939 | + let cases = lits.into_iter().zip(bodies.by_ref()).collect(); |
| 940 | + let default = Box::new(bodies.next().expect("the default's body")); |
| 941 | + *b = Expr::SwitchLit { on, cases, default }; |
| 942 | + } |
| 943 | + end => { |
| 944 | + *b = end; |
| 945 | + } |
| 946 | + } |
| 947 | +} |
| 948 | + |
| 949 | +/// Rebuild an expression from its chain and its end (`split` reversed). |
| 950 | +pub(crate) fn rebuild(lets: Vec<(VarId, Value, Option<Span>)>, end: Expr) -> Expr { |
| 951 | + let mut out = end; |
| 952 | + for (v, value, span) in lets.into_iter().rev() { |
| 953 | + out = Expr::Let(v, Box::new(value), Box::new(out), span); |
| 954 | + } |
| 955 | + out |
| 956 | +} |
| 957 | + |
| 958 | +/// `e` with its variables replaced: inlining renames a callee's |
| 959 | +/// variables into the caller's (its parameters to the arguments, the |
| 960 | +/// rest fresh). |
| 961 | +fn rename(e: &Expr, m: &mut dyn FnMut(VarId) -> Atom) -> Expr { |
| 962 | + match e { |
| 963 | + Expr::Let(v, value, rest, span) => { |
| 964 | + let Atom::Var(v) = m(*v) else { |
| 965 | + unreachable!("a parameter is never `let`-bound") |
| 966 | + }; |
| 967 | + Expr::Let( |
| 968 | + v, |
| 969 | + Box::new(rename_value(value, m)), |
| 970 | + Box::new(rename(rest, m)), |
| 971 | + *span, |
| 972 | + ) |
| 973 | + } |
| 974 | + Expr::Return(a) => Expr::Return(rename_atom(a, m)), |
| 975 | + Expr::Exit(a) => Expr::Exit(rename_atom(a, m)), |
| 976 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 977 | + on: rename_atom(on, m), |
| 978 | + cases: cases.iter().map(|(t, b)| (*t, rename(b, m))).collect(), |
| 979 | + default: default.as_ref().map(|d| Box::new(rename(d, m))), |
| 980 | + }, |
| 981 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 982 | + on: rename_atom(on, m), |
| 983 | + cases: cases |
| 984 | + .iter() |
| 985 | + .map(|(c, b)| (c.clone(), rename(b, m))) |
| 986 | + .collect(), |
| 987 | + default: Box::new(rename(default, m)), |
| 988 | + }, |
| 989 | + Expr::Panic(p) => Expr::Panic(p.clone()), |
| 990 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 991 | + unreachable!("Core before Perceus") |
| 992 | + } |
| 993 | + Expr::ReturnN(_) | Expr::LetN(..) => unreachable!("Core before the CPR pass"), |
| 994 | + } |
| 995 | +} |
| 996 | + |
| 997 | +fn rename_atom(a: &Atom, m: &mut dyn FnMut(VarId) -> Atom) -> Atom { |
| 998 | + match a { |
| 999 | + Atom::Var(v) => m(*v), |
| 1000 | + a => a.clone(), |
| 1001 | + } |
| 1002 | +} |
| 1003 | + |
| 1004 | +fn rename_value(v: &Value, m: &mut dyn FnMut(VarId) -> Atom) -> Value { |
| 1005 | + match v { |
| 1006 | + Value::Atom(a) => Value::Atom(rename_atom(a, m)), |
| 1007 | + Value::Call(f, args) => Value::Call(rename_atom(f, m), rename_atoms(args, m)), |
| 1008 | + Value::CallFn(g, args) => Value::CallFn(*g, rename_atoms(args, m)), |
| 1009 | + Value::CallExtern(s, args) => Value::CallExtern(s.clone(), rename_atoms(args, m)), |
| 1010 | + Value::Prim(p, args) => Value::Prim(*p, rename_atoms(args, m)), |
| 1011 | + Value::Construct { tag, name, args } => Value::Construct { |
| 1012 | + tag: *tag, |
| 1013 | + name: name.clone(), |
| 1014 | + args: rename_atoms(args, m), |
| 1015 | + }, |
| 1016 | + Value::Tuple(args) => Value::Tuple(rename_atoms(args, m)), |
| 1017 | + Value::Field(a, i) => Value::Field(rename_atom(a, m), *i), |
| 1018 | + Value::Closure(g, caps) => Value::Closure(*g, rename_atoms(caps, m)), |
| 1019 | + Value::Perform { |
| 1020 | + cap, |
| 1021 | + effect, |
| 1022 | + op, |
| 1023 | + args, |
| 1024 | + } => Value::Perform { |
| 1025 | + cap: rename_atom(cap, m), |
| 1026 | + effect: *effect, |
| 1027 | + op: *op, |
| 1028 | + args: rename_atoms(args, m), |
| 1029 | + }, |
| 1030 | + Value::Handle { |
| 1031 | + effect, |
| 1032 | + body, |
| 1033 | + ret, |
| 1034 | + clauses, |
| 1035 | + } => Value::Handle { |
| 1036 | + effect: *effect, |
| 1037 | + body: rename_atom(body, m), |
| 1038 | + ret: ret.as_ref().map(|r| rename_atom(r, m)), |
| 1039 | + clauses: rename_atoms(clauses, m), |
| 1040 | + }, |
| 1041 | + Value::Region { effects, body } => Value::Region { |
| 1042 | + effects: effects.clone(), |
| 1043 | + body: rename_atom(body, m), |
| 1044 | + }, |
| 1045 | + Value::Defer { body, cleanup } => Value::Defer { |
| 1046 | + body: rename_atom(body, m), |
| 1047 | + cleanup: rename_atom(cleanup, m), |
| 1048 | + }, |
| 1049 | + Value::Block(b) => Value::Block(Box::new(rename(b, m))), |
| 1050 | + Value::Reuse { .. } | Value::CtxExtend { .. } | Value::CtxApply { .. } => { |
| 1051 | + unreachable!("Core before TRMC and Perceus") |
| 1052 | + } |
| 1053 | + } |
| 1054 | +} |
| 1055 | + |
| 1056 | +fn rename_atoms(atoms: &[Atom], m: &mut dyn FnMut(VarId) -> Atom) -> Vec<Atom> { |
| 1057 | + atoms.iter().map(|a| rename_atom(a, m)).collect() |
| 1058 | +} |
| 1059 | + |
| 1060 | +/// Every variable a `let` binds in `e`, anywhere in it. |
| 1061 | +fn collect_bound(e: &Expr, out: &mut BTreeSet<VarId>) { |
| 1062 | + visit_exprs(e, &mut |e| { |
| 1063 | + if let Expr::Let(v, _, _, _) = e { |
| 1064 | + out.insert(*v); |
| 1065 | + } |
| 1066 | + }); |
| 1067 | +} |
| 1068 | + |
| 1069 | +/// The chain a body is: how its value leaves it. |
| 1070 | +fn end_of(e: &Expr) -> End { |
| 1071 | + let mut e = e; |
| 1072 | + loop { |
| 1073 | + match e { |
| 1074 | + Expr::Let(_, _, rest, _) => e = rest, |
| 1075 | + Expr::LetN(_, _, rest, _) => e = rest, |
| 1076 | + Expr::Return(_) | Expr::ReturnN(_) => return End::Return, |
| 1077 | + Expr::Panic(_) => return End::Panic, |
| 1078 | + _ => return End::Other, |
| 1079 | + } |
| 1080 | + } |
| 1081 | +} |
| 1082 | + |
| 1083 | +/// Whether the expression's chain ends in a switch. |
| 1084 | +fn ends_in_switch(e: &Expr) -> bool { |
| 1085 | + let mut e = e; |
| 1086 | + loop { |
| 1087 | + match e { |
| 1088 | + Expr::Let(_, _, rest, _) => e = rest, |
| 1089 | + Expr::Switch { .. } => return true, |
| 1090 | + _ => return false, |
| 1091 | + } |
| 1092 | + } |
| 1093 | +} |
| 1094 | + |
| 1095 | +/// Whether a block-switch is free of effects and panics, so its `let`s |
| 1096 | +/// may move past what follows the block (case-of-case): only pure values |
| 1097 | +/// and primitives, and externs that can neither perform nor panic |
| 1098 | +/// (`pure::extern_pure`, fusion's gate shared). |
| 1099 | +fn block_pure(e: &Expr) -> bool { |
| 1100 | + let mut ok = true; |
| 1101 | + visit_exprs(e, &mut |e| { |
| 1102 | + if !ok { |
| 1103 | + return; |
| 1104 | + } |
| 1105 | + match e { |
| 1106 | + Expr::Panic(_) => ok = false, |
| 1107 | + Expr::Let(_, value, _, _) => match value.as_ref() { |
| 1108 | + Value::Atom(_) |
| 1109 | + | Value::Field(..) |
| 1110 | + | Value::Prim(..) |
| 1111 | + | Value::Tuple(_) |
| 1112 | + | Value::Construct { .. } |
| 1113 | + | Value::Closure(..) |
| 1114 | + | Value::Block(_) => {} |
| 1115 | + Value::CallExtern(symbol, args) => { |
| 1116 | + if !super::pure::extern_pure(symbol, args) { |
| 1117 | + ok = false; |
| 1118 | + } |
| 1119 | + } |
| 1120 | + _ => ok = false, |
| 1121 | + }, |
| 1122 | + _ => {} |
| 1123 | + } |
| 1124 | + }); |
| 1125 | + ok |
| 1126 | +} |
| 1127 | + |
| 1128 | +/// Whether the body calls function `id`, or closes over it, anywhere. |
| 1129 | +fn recursive(e: &Expr, id: FnId) -> bool { |
| 1130 | + let mut found = false; |
| 1131 | + visit_values(e, &mut |v| { |
| 1132 | + if matches!(v, Value::CallFn(g, _) | Value::Closure(g, _) if *g == id) { |
| 1133 | + found = true; |
| 1134 | + } |
| 1135 | + }); |
| 1136 | + found |
| 1137 | +} |
| 1138 | + |
| 1139 | +/// Whether the body leaves its function early (ADR 0037), anywhere. |
| 1140 | +fn has_exit(e: &Expr) -> bool { |
| 1141 | + let mut found = false; |
| 1142 | + visit_exprs(e, &mut |e| { |
| 1143 | + if matches!(e, Expr::Exit(_)) { |
| 1144 | + found = true; |
| 1145 | + } |
| 1146 | + }); |
| 1147 | + found |
| 1148 | +} |
| 1149 | + |
| 1150 | +/// An upper bound on a body's size in nodes (lets, values, branches), |
| 1151 | +/// saturating where the caps stop mattering. |
| 1152 | +fn size(e: &Expr) -> u32 { |
| 1153 | + let mut n = 0u32; |
| 1154 | + visit_exprs(e, &mut |_| { |
| 1155 | + n = n.saturating_add(1); |
| 1156 | + }); |
| 1157 | + let mut m = 0u32; |
| 1158 | + visit_values(e, &mut |_| { |
| 1159 | + m = m.saturating_add(1); |
| 1160 | + }); |
| 1161 | + n + m |
| 1162 | +} |
| 1163 | + |
| 1164 | +/// Every expression node, anywhere in `e` (analysis only: it accepts |
| 1165 | +/// every node, whenever it runs). |
| 1166 | +pub(crate) fn visit_exprs(e: &Expr, f: &mut impl FnMut(&Expr)) { |
| 1167 | + let mut work = vec![e]; |
| 1168 | + while let Some(e) = work.pop() { |
| 1169 | + f(e); |
| 1170 | + match e { |
| 1171 | + Expr::Let(_, value, rest, _) => { |
| 1172 | + if let Value::Block(b) = &**value { |
| 1173 | + work.push(b); |
| 1174 | + } |
| 1175 | + work.push(rest); |
| 1176 | + } |
| 1177 | + Expr::LetN(_, value, rest, _) => { |
| 1178 | + if let Value::Block(b) = &**value { |
| 1179 | + work.push(b); |
| 1180 | + } |
| 1181 | + work.push(rest); |
| 1182 | + } |
| 1183 | + Expr::Switch { cases, default, .. } => { |
| 1184 | + for (_, b) in cases { |
| 1185 | + work.push(b); |
| 1186 | + } |
| 1187 | + if let Some(d) = default { |
| 1188 | + work.push(d); |
| 1189 | + } |
| 1190 | + } |
| 1191 | + Expr::SwitchLit { cases, default, .. } => { |
| 1192 | + for (_, b) in cases { |
| 1193 | + work.push(b); |
| 1194 | + } |
| 1195 | + work.push(default); |
| 1196 | + } |
| 1197 | + _ => {} |
| 1198 | + } |
| 1199 | + } |
| 1200 | +} |
| 1201 | + |
| 1202 | +/// Every value node, anywhere in `e`. |
| 1203 | +pub(crate) fn visit_values(e: &Expr, f: &mut impl FnMut(&Value)) { |
| 1204 | + visit_exprs(e, &mut |e| { |
| 1205 | + if let Expr::Let(_, value, _, _) = e { |
| 1206 | + f(value); |
| 1207 | + } |
| 1208 | + }); |
| 1209 | +} |
| 1210 | + |
| 1211 | +/// Every atom in a use position, anywhere in `e`. |
| 1212 | +pub(crate) fn visit(e: &Expr, f: &mut impl FnMut(&Atom)) { |
| 1213 | + visit_exprs(e, &mut |e| match e { |
| 1214 | + Expr::Let(_, value, _, _) => visit_value(value, f), |
| 1215 | + Expr::LetN(_, value, _, _) => visit_value(value, f), |
| 1216 | + Expr::Return(a) | Expr::Exit(a) => f(a), |
| 1217 | + Expr::ReturnN(atoms) => { |
| 1218 | + for a in atoms { |
| 1219 | + f(a); |
| 1220 | + } |
| 1221 | + } |
| 1222 | + Expr::Switch { on, .. } | Expr::SwitchLit { on, .. } => f(on), |
| 1223 | + Expr::Dup(v, _) | Expr::Drop(v, _) => f(&Atom::Var(*v)), |
| 1224 | + Expr::Release { |
| 1225 | + var, fields, token, .. |
| 1226 | + } => { |
| 1227 | + f(&Atom::Var(*var)); |
| 1228 | + for (_, v) in fields { |
| 1229 | + f(&Atom::Var(*v)); |
| 1230 | + } |
| 1231 | + if let Some(t) = token { |
| 1232 | + f(&Atom::Var(*t)); |
| 1233 | + } |
| 1234 | + } |
| 1235 | + Expr::Panic(_) => {} |
| 1236 | + }); |
| 1237 | +} |
| 1238 | + |
| 1239 | +fn visit_value(v: &Value, f: &mut impl FnMut(&Atom)) { |
| 1240 | + match v { |
| 1241 | + Value::Atom(a) => f(a), |
| 1242 | + Value::Call(g, args) => { |
| 1243 | + f(g); |
| 1244 | + for a in args { |
| 1245 | + f(a); |
| 1246 | + } |
| 1247 | + } |
| 1248 | + Value::CallFn(_, args) |
| 1249 | + | Value::CallExtern(_, args) |
| 1250 | + | Value::Prim(_, args) |
| 1251 | + | Value::Tuple(args) |
| 1252 | + | Value::Construct { args, .. } |
| 1253 | + | Value::Closure(_, args) => { |
| 1254 | + for a in args { |
| 1255 | + f(a); |
| 1256 | + } |
| 1257 | + } |
| 1258 | + Value::Field(a, _) => f(a), |
| 1259 | + Value::Perform { cap, args, .. } => { |
| 1260 | + f(cap); |
| 1261 | + for a in args { |
| 1262 | + f(a); |
| 1263 | + } |
| 1264 | + } |
| 1265 | + Value::Handle { |
| 1266 | + body, ret, clauses, .. |
| 1267 | + } => { |
| 1268 | + f(body); |
| 1269 | + if let Some(r) = ret { |
| 1270 | + f(r); |
| 1271 | + } |
| 1272 | + for a in clauses { |
| 1273 | + f(a); |
| 1274 | + } |
| 1275 | + } |
| 1276 | + Value::Region { body, .. } => f(body), |
| 1277 | + Value::Defer { body, cleanup } => { |
| 1278 | + f(body); |
| 1279 | + f(cleanup); |
| 1280 | + } |
| 1281 | + Value::Block(_) => {} // `visit_exprs` walks into blocks |
| 1282 | + Value::Reuse { token, value, .. } => { |
| 1283 | + f(&Atom::Var(*token)); |
| 1284 | + visit_value(value, f); |
| 1285 | + } |
| 1286 | + Value::CtxExtend { ctx, cell, .. } => { |
| 1287 | + f(ctx); |
| 1288 | + f(cell); |
| 1289 | + } |
| 1290 | + Value::CtxApply { ctx, value } => { |
| 1291 | + f(ctx); |
| 1292 | + f(value); |
| 1293 | + } |
| 1294 | + } |
| 1295 | +} |
| 1296 | + |
| 1297 | +fn var(a: &Atom, used: &mut HashSet<VarId>) { |
| 1298 | + if let Atom::Var(v) = a { |
| 1299 | + used.insert(*v); |
| 1300 | + } |
| 1301 | +} |
| 1302 | + |
| 1303 | +fn value_vars(value: &Value, used: &mut HashSet<VarId>) { |
| 1304 | + visit_value(value, &mut |a| var(a, used)); |
| 1305 | +} |
| 1306 | + |
| 1307 | +/// The variables used anywhere in `e`, and how often. |
| 1308 | +pub(crate) fn uses(e: &Expr) -> HashMap<VarId, u32> { |
| 1309 | + let mut out: HashMap<VarId, u32> = HashMap::new(); |
| 1310 | + visit(e, &mut |a| { |
| 1311 | + if let Atom::Var(v) = a { |
| 1312 | + *out.entry(*v).or_insert(0) += 1; |
| 1313 | + } |
| 1314 | + }); |
| 1315 | + out |
| 1316 | +} |
| 1317 | + |
| 1318 | +/// The variables used anywhere in `e`. |
| 1319 | +fn free_vars(e: &Expr) -> HashSet<VarId> { |
| 1320 | + let mut out = HashSet::new(); |
| 1321 | + visit(e, &mut |a| var(a, &mut out)); |
| 1322 | + out |
| 1323 | +} |