| @@ -0,0 +1,433 @@ |
| 1 | +//! Constructed product results (issue #200, ADR 0043): a function whose |
| 2 | +//! every exit builds the same small tuple returns its components without |
| 3 | +//! allocating the tuple, through a worker/wrapper split. |
| 4 | +//! |
| 5 | +//! `divmod`'s caller usually destructures right away (`let (q, r) = |
| 6 | +//! divmod(a, b)`). So a function whose exits all return a fresh tuple of |
| 7 | +//! 2–4 components gets a **worker** `f$wrk`: a copy whose exits are |
| 8 | +//! `ReturnN` with the components, which the C backend emits as a small |
| 9 | +//! struct returned by value (two words come back in registers on the |
| 10 | +//! platform ABIs). A call site that immediately destructures the result |
| 11 | +//! becomes a `LetN` binding the components from the worker's call, so the |
| 12 | +//! tuple is never built on that path. The wrapper keeps the original body |
| 13 | +//! and serves closures and unknown callers. |
| 14 | +//! |
| 15 | +//! Runs after the simplify/fuse/specialise fixed point, before TRMC and |
| 16 | +//! Perceus: Perceus counts the components as ordinary owned values (the |
| 17 | +//! tuple is never built on worker paths), and TRMC sees no site in a |
| 18 | +//! worker (its exits are `ReturnN`, not a constructor spine). A function |
| 19 | +//! is eligible when its body has no `exit` (v1), at most six parameters |
| 20 | +//! (the worker keeps the register signature), and every exit either |
| 21 | +//! returns a fresh tuple of the shared arity or tail-calls the function |
| 22 | +//! itself (a self-call in the worker calls the worker). Tuples only, for |
| 23 | +//! now; single-constructor records are the same analysis plus a tag. |
| 24 | + |
| 25 | +use std::collections::{HashMap, HashSet}; |
| 26 | + |
| 27 | +use super::simplify::{split, visit, visit_exprs}; |
| 28 | +use crate::ir::{Atom, Expr, FnDecl, FnId, Program, Span, Value, VarId}; |
| 29 | + |
| 30 | +/// Tuples of at most this many fields are unboxed. |
| 31 | +const MAX_COMPONENTS: u32 = 4; |
| 32 | + |
| 33 | +/// What a variable is bound to, for the exit analysis. |
| 34 | +enum Produced { |
| 35 | + /// A fresh tuple, with these components. |
| 36 | + Tuple(Vec<Atom>), |
| 37 | + /// A call of the function itself (its result is the same shape). |
| 38 | + SelfCall, |
| 39 | + /// A block; the tuple is produced in its arms. |
| 40 | + Block(Expr), |
| 41 | + /// Anything else: not a candidate. |
| 42 | + Other, |
| 43 | +} |
| 44 | + |
| 45 | +/// The CPR pass over the functions in `live`: make workers for the |
| 46 | +/// eligible and rewrite the destructuring call sites to them. |
| 47 | +pub fn run_in(program: &mut Program, live: &[FnId]) { |
| 48 | + if std::env::var_os("LOUISE_NO_CPR").is_some() { |
| 49 | + return; |
| 50 | + } |
| 51 | + let mut workers: HashMap<FnId, (FnId, u32)> = HashMap::new(); |
| 52 | + for &id in live { |
| 53 | + let f = &program.fns[id as usize]; |
| 54 | + if f.fip || f.cpr_arity.is_some() || f.params.len() > 6 { |
| 55 | + continue; |
| 56 | + } |
| 57 | + let body = f.body.clone(); |
| 58 | + let defs = produced(&body, id); |
| 59 | + let Some(arity) = analyse(&body, &defs) else { |
| 60 | + continue; |
| 61 | + }; |
| 62 | + // A placeholder gets the worker's id before its body exists. |
| 63 | + let worker = program.fns.len() as FnId; |
| 64 | + let name = format!("{}$wrk", f.name); |
| 65 | + let (params, span, shapes) = { |
| 66 | + let f = &program.fns[id as usize]; |
| 67 | + (f.params.clone(), f.span, f.shapes.clone()) |
| 68 | + }; |
| 69 | + program.fns.push(FnDecl { |
| 70 | + name, |
| 71 | + params, |
| 72 | + body: Expr::Panic("a CPR worker before its body".to_owned()), |
| 73 | + n_vars: f.n_vars, |
| 74 | + borrowed: Default::default(), |
| 75 | + span, |
| 76 | + // Generated: the `+specialised` unit (ADR 0029). |
| 77 | + module: None, |
| 78 | + shapes, |
| 79 | + fip: false, |
| 80 | + cpr_arity: Some(arity), |
| 81 | + }); |
| 82 | + let mut next_var = program.fns[id as usize].n_vars; |
| 83 | + let mut dead = HashSet::new(); |
| 84 | + match rewrite(body, id, worker, arity, &defs, &mut next_var, &mut dead) { |
| 85 | + Some(new_body) => { |
| 86 | + let w = &mut program.fns[worker as usize]; |
| 87 | + w.body = new_body; |
| 88 | + w.n_vars = next_var; |
| 89 | + workers.insert(id, (worker, arity)); |
| 90 | + } |
| 91 | + None => { |
| 92 | + program.fns.pop(); // not eligible after all |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + if workers.is_empty() { |
| 97 | + return; |
| 98 | + } |
| 99 | + for &id in live { |
| 100 | + let body = std::mem::replace(&mut program.fns[id as usize].body, Expr::Return(Atom::Unit)); |
| 101 | + let uses = uses_of(&body); |
| 102 | + program.fns[id as usize].body = rewrite_sites(body, &workers, &uses); |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +/// What every variable in `body` is bound to, for the exit analysis. |
| 107 | +fn produced(body: &Expr, self_: FnId) -> HashMap<VarId, Produced> { |
| 108 | + let mut out = HashMap::new(); |
| 109 | + visit_exprs(body, &mut |e| { |
| 110 | + if let Expr::Let(v, value, _, _) = e { |
| 111 | + let p = match &**value { |
| 112 | + Value::Tuple(args) => Produced::Tuple(args.clone()), |
| 113 | + Value::CallFn(g, _) if *g == self_ => Produced::SelfCall, |
| 114 | + Value::Block(b) => Produced::Block((**b).clone()), |
| 115 | + _ => Produced::Other, |
| 116 | + }; |
| 117 | + out.insert(*v, p); |
| 118 | + } |
| 119 | + }); |
| 120 | + out |
| 121 | +} |
| 122 | + |
| 123 | +/// The arity `f` returns everywhere as a fresh tuple, if eligible: the |
| 124 | +/// exit-driven check (see the module docs). |
| 125 | +fn analyse(body: &Expr, defs: &HashMap<VarId, Produced>) -> Option<u32> { |
| 126 | + // v1: no `exit` anywhere, and no recursion (a self-tail-call in a |
| 127 | + // worker would need the tail jump, which a borrowed parameter's |
| 128 | + // drop defeats — left to a follow-up). |
| 129 | + let mut has_exit = false; |
| 130 | + visit_exprs(body, &mut |e| has_exit |= matches!(e, Expr::Exit(_))); |
| 131 | + if has_exit || defs.values().any(|p| matches!(p, Produced::SelfCall)) { |
| 132 | + return None; |
| 133 | + } |
| 134 | + exits_arity(body, defs).ok()? |
| 135 | +} |
| 136 | + |
| 137 | +/// The arity every exit of `e` returns as a fresh tuple. `Ok(None)` is |
| 138 | +/// "no exit here constrains it" (a panic or a self-call); `Err(())` is |
| 139 | +/// "an exit that doesn't fit". |
| 140 | +#[allow(clippy::collapsible_match)] |
| 141 | +fn exits_arity(e: &Expr, defs: &HashMap<VarId, Produced>) -> Result<Option<u32>, ()> { |
| 142 | + let (_, end) = split(e.clone()); |
| 143 | + match end { |
| 144 | + Expr::Return(Atom::Var(v)) => match defs.get(&v) { |
| 145 | + Some(Produced::Tuple(args)) => { |
| 146 | + let n = args.len() as u32; |
| 147 | + if (2..=MAX_COMPONENTS).contains(&n) { |
| 148 | + Ok(Some(n)) |
| 149 | + } else { |
| 150 | + Err(()) |
| 151 | + } |
| 152 | + } |
| 153 | + Some(Produced::SelfCall) => Ok(None), |
| 154 | + Some(Produced::Block(b)) => exits_arity(b, defs), |
| 155 | + _ => Err(()), |
| 156 | + }, |
| 157 | + Expr::Exit(_) => Err(()), |
| 158 | + Expr::Switch { cases, default, .. } => { |
| 159 | + let mut arity = None; |
| 160 | + for (_, b) in &cases { |
| 161 | + arity = merge(arity, exits_arity(b, defs)?)?; |
| 162 | + } |
| 163 | + if let Some(d) = default { |
| 164 | + arity = merge(arity, exits_arity(&d, defs)?)?; |
| 165 | + } |
| 166 | + Ok(arity) |
| 167 | + } |
| 168 | + Expr::SwitchLit { cases, default, .. } => { |
| 169 | + let mut arity = None; |
| 170 | + for (_, b) in &cases { |
| 171 | + arity = merge(arity, exits_arity(b, defs)?)?; |
| 172 | + } |
| 173 | + merge(arity, exits_arity(&default, defs)?) |
| 174 | + } |
| 175 | + Expr::Panic(_) => Ok(None), |
| 176 | + _ => Err(()), |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +/// Merge two arity observations: they must agree where both present. |
| 181 | +fn merge(a: Option<u32>, b: Option<u32>) -> Result<Option<u32>, ()> { |
| 182 | + match (a, b) { |
| 183 | + (Some(x), Some(y)) if x != y => Err(()), |
| 184 | + (x, y) => Ok(x.or(y)), |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +/// Rewrite `e`'s exits to `ReturnN` and its tail self-calls to the |
| 189 | +/// worker. `arity` is known from the analysis. `dead` collects the tuple |
| 190 | +/// constructions the rewrite leaves unused. |
| 191 | +#[allow(clippy::collapsible_match)] |
| 192 | +fn rewrite( |
| 193 | + e: Expr, |
| 194 | + self_: FnId, |
| 195 | + worker: FnId, |
| 196 | + arity: u32, |
| 197 | + defs: &HashMap<VarId, Produced>, |
| 198 | + next_var: &mut u32, |
| 199 | + dead: &mut HashSet<VarId>, |
| 200 | +) -> Option<Expr> { |
| 201 | + let (lets, end) = split(e); |
| 202 | + let mut out: Vec<(VarId, Value, Option<Span>)> = Vec::with_capacity(lets.len()); |
| 203 | + let n = lets.len(); |
| 204 | + for (i, (v, value, span)) in lets.into_iter().enumerate() { |
| 205 | + // A tail self-call: `let t = f(…); return t` with f this |
| 206 | + // function. In the worker it calls the worker and returns the |
| 207 | + // components it binds. |
| 208 | + if i + 1 == n |
| 209 | + && let Value::CallFn(g, args) = &value |
| 210 | + && *g == self_ |
| 211 | + && matches!(&end, Expr::Return(Atom::Var(r)) if *r == v) |
| 212 | + { |
| 213 | + let comps: Vec<VarId> = (0..arity) |
| 214 | + .map(|_| { |
| 215 | + let fresh = *next_var; |
| 216 | + *next_var += 1; |
| 217 | + fresh |
| 218 | + }) |
| 219 | + .collect(); |
| 220 | + let call = Expr::LetN( |
| 221 | + comps.clone(), |
| 222 | + Box::new(Value::CallFn(worker, args.clone())), |
| 223 | + Box::new(Expr::ReturnN(comps.iter().map(|c| Atom::Var(*c)).collect())), |
| 224 | + span, |
| 225 | + ); |
| 226 | + return Some(finish_chain(out, call, dead)); |
| 227 | + } |
| 228 | + // A value-block's arms produce values, not the function's exits: |
| 229 | + // leave them alone. |
| 230 | + out.push((v, value, span)); |
| 231 | + } |
| 232 | + match end { |
| 233 | + Expr::Return(a) => match a { |
| 234 | + Atom::Var(v) => match defs.get(&v)? { |
| 235 | + Produced::Tuple(args) => { |
| 236 | + dead.insert(v); // the tuple is never built on this path |
| 237 | + Some(finish_chain(out, Expr::ReturnN(args.clone()), dead)) |
| 238 | + } |
| 239 | + // `let v = { block producing the tuple }; return v`: the |
| 240 | + // block in tail position rewrites to `ReturnN` arms and |
| 241 | + // becomes the chain's end. |
| 242 | + Produced::Block(b) => { |
| 243 | + let b = rewrite(b.clone(), self_, worker, arity, defs, next_var, dead)?; |
| 244 | + dead.insert(v); |
| 245 | + Some(finish_chain(out, b, dead)) |
| 246 | + } |
| 247 | + _ => None, |
| 248 | + }, |
| 249 | + _ => None, |
| 250 | + }, |
| 251 | + Expr::Switch { on, cases, default } => { |
| 252 | + let mut new_cases = Vec::new(); |
| 253 | + for (t, b) in cases { |
| 254 | + new_cases.push((t, rewrite(b, self_, worker, arity, defs, next_var, dead)?)); |
| 255 | + } |
| 256 | + let new_default = match default { |
| 257 | + Some(d) => Some(Box::new(rewrite( |
| 258 | + *d, self_, worker, arity, defs, next_var, dead, |
| 259 | + )?)), |
| 260 | + None => None, |
| 261 | + }; |
| 262 | + Some(finish_chain( |
| 263 | + out, |
| 264 | + Expr::Switch { |
| 265 | + on, |
| 266 | + cases: new_cases, |
| 267 | + default: new_default, |
| 268 | + }, |
| 269 | + dead, |
| 270 | + )) |
| 271 | + } |
| 272 | + Expr::SwitchLit { on, cases, default } => { |
| 273 | + let mut new_cases = Vec::new(); |
| 274 | + for (c, b) in cases { |
| 275 | + new_cases.push((c, rewrite(b, self_, worker, arity, defs, next_var, dead)?)); |
| 276 | + } |
| 277 | + let new_default = rewrite(*default, self_, worker, arity, defs, next_var, dead)?; |
| 278 | + Some(finish_chain( |
| 279 | + out, |
| 280 | + Expr::SwitchLit { |
| 281 | + on, |
| 282 | + cases: new_cases, |
| 283 | + default: Box::new(new_default), |
| 284 | + }, |
| 285 | + dead, |
| 286 | + )) |
| 287 | + } |
| 288 | + end @ Expr::Panic(_) => Some(finish_chain(out, end, dead)), |
| 289 | + _ => None, |
| 290 | + } |
| 291 | +} |
| 292 | + |
| 293 | +/// Rebuild a chain from its `let`s and its new end, dropping `dead` lets |
| 294 | +/// (the tuple constructions the rewrite made unused). |
| 295 | +fn finish_chain(out: Vec<(VarId, Value, Option<Span>)>, end: Expr, dead: &HashSet<VarId>) -> Expr { |
| 296 | + let mut e = end; |
| 297 | + for (v, value, span) in out.into_iter().rev() { |
| 298 | + if dead.contains(&v) { |
| 299 | + continue; |
| 300 | + } |
| 301 | + e = Expr::Let(v, Box::new(value), Box::new(e), span); |
| 302 | + } |
| 303 | + e |
| 304 | +} |
| 305 | + |
| 306 | +/// How often each variable is used in `e` (a call-site rewrite's "the |
| 307 | +/// tuple is destructured and never otherwise used" check). |
| 308 | +fn uses_of(body: &Expr) -> HashMap<VarId, u32> { |
| 309 | + let mut out: HashMap<VarId, u32> = HashMap::new(); |
| 310 | + visit(body, &mut |a| { |
| 311 | + if let Atom::Var(v) = a { |
| 312 | + *out.entry(*v).or_default() += 1; |
| 313 | + } |
| 314 | + }); |
| 315 | + out |
| 316 | +} |
| 317 | + |
| 318 | +/// Rewrite the destructuring call sites of `workers` in `body`: |
| 319 | +/// `let t = f(args); let a = t.0; let b = t.1; …` becomes |
| 320 | +/// `let (a, b, …) = f$wrk(args)`. |
| 321 | +fn rewrite_sites( |
| 322 | + body: Expr, |
| 323 | + workers: &HashMap<FnId, (FnId, u32)>, |
| 324 | + uses: &HashMap<VarId, u32>, |
| 325 | +) -> Expr { |
| 326 | + let (lets, end) = split(body); |
| 327 | + rewrite_chain(lets, end, workers, uses) |
| 328 | +} |
| 329 | + |
| 330 | +fn rewrite_chain( |
| 331 | + lets: Vec<(VarId, Value, Option<Span>)>, |
| 332 | + end: Expr, |
| 333 | + workers: &HashMap<FnId, (FnId, u32)>, |
| 334 | + uses: &HashMap<VarId, u32>, |
| 335 | +) -> Expr { |
| 336 | + let mut out: Vec<(VarId, Value, Option<Span>)> = Vec::with_capacity(lets.len()); |
| 337 | + let mut i = 0; |
| 338 | + while i < lets.len() { |
| 339 | + let (v, value, span) = &lets[i]; |
| 340 | + // A block value may hold a site itself. |
| 341 | + let value = match value { |
| 342 | + Value::Block(b) => Value::Block(Box::new(rewrite_sites((**b).clone(), workers, uses))), |
| 343 | + value => value.clone(), |
| 344 | + }; |
| 345 | + if let Value::CallFn(f, args) = &value |
| 346 | + && let Some(&(worker, arity)) = workers.get(f) |
| 347 | + && let Some((vars, next)) = try_destructure(&lets, i, *v, arity, uses) |
| 348 | + { |
| 349 | + // The rest of the chain after the projections, rewritten too. |
| 350 | + let rest = rewrite_chain(lets[next..].to_vec(), end, workers, uses); |
| 351 | + let letn = Expr::LetN( |
| 352 | + vars, |
| 353 | + Box::new(Value::CallFn(worker, args.clone())), |
| 354 | + Box::new(rest), |
| 355 | + *span, |
| 356 | + ); |
| 357 | + return rebuild_lets(out, letn); |
| 358 | + } |
| 359 | + out.push((*v, value, *span)); |
| 360 | + i += 1; |
| 361 | + } |
| 362 | + rebuild_lets(out, rewrite_end(end, workers, uses)) |
| 363 | +} |
| 364 | + |
| 365 | +/// Whether the lets after `lets[i]` are exactly the projections of every |
| 366 | +/// field of its result (the tuple is destructured and not otherwise |
| 367 | +/// used). The component variables in field order, and the index after. |
| 368 | +fn try_destructure( |
| 369 | + lets: &[(VarId, Value, Option<Span>)], |
| 370 | + i: usize, |
| 371 | + result: VarId, |
| 372 | + arity: u32, |
| 373 | + uses: &HashMap<VarId, u32>, |
| 374 | +) -> Option<(Vec<VarId>, usize)> { |
| 375 | + let arity = arity as usize; |
| 376 | + let mut fields: Vec<Option<VarId>> = vec![None; arity]; |
| 377 | + let mut j = i + 1; |
| 378 | + while j < lets.len() { |
| 379 | + let (w, wv, _) = &lets[j]; |
| 380 | + match wv { |
| 381 | + Value::Field(Atom::Var(base), idx) |
| 382 | + if *base == result |
| 383 | + && (*idx as usize) < arity |
| 384 | + && fields[*idx as usize].is_none() => |
| 385 | + { |
| 386 | + fields[*idx as usize] = Some(*w); |
| 387 | + j += 1; |
| 388 | + } |
| 389 | + _ => break, |
| 390 | + } |
| 391 | + } |
| 392 | + // All fields destructured, and the tuple used nowhere else. |
| 393 | + if fields.iter().all(|f| f.is_some()) && uses.get(&result).copied() == Some(arity as u32) { |
| 394 | + let vars = fields.into_iter().map(|f| f.expect("all fields")).collect(); |
| 395 | + Some((vars, j)) |
| 396 | + } else { |
| 397 | + None |
| 398 | + } |
| 399 | +} |
| 400 | + |
| 401 | +fn rewrite_end( |
| 402 | + end: Expr, |
| 403 | + workers: &HashMap<FnId, (FnId, u32)>, |
| 404 | + uses: &HashMap<VarId, u32>, |
| 405 | +) -> Expr { |
| 406 | + match end { |
| 407 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 408 | + on, |
| 409 | + cases: cases |
| 410 | + .into_iter() |
| 411 | + .map(|(t, b)| (t, rewrite_sites(b, workers, uses))) |
| 412 | + .collect(), |
| 413 | + default: default.map(|d| Box::new(rewrite_sites(*d, workers, uses))), |
| 414 | + }, |
| 415 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 416 | + on, |
| 417 | + cases: cases |
| 418 | + .into_iter() |
| 419 | + .map(|(c, b)| (c, rewrite_sites(b, workers, uses))) |
| 420 | + .collect(), |
| 421 | + default: Box::new(rewrite_sites(*default, workers, uses)), |
| 422 | + }, |
| 423 | + e => e, |
| 424 | + } |
| 425 | +} |
| 426 | + |
| 427 | +fn rebuild_lets(lets: Vec<(VarId, Value, Option<Span>)>, end: Expr) -> Expr { |
| 428 | + let mut e = end; |
| 429 | + for (v, value, span) in lets.into_iter().rev() { |
| 430 | + e = Expr::Let(v, Box::new(value), Box::new(e), span); |
| 431 | + } |
| 432 | + e |
| 433 | +} |