| @@ -3,8 +3,10 @@ |
| 3 | 3 | //! |
| 4 | 4 | //! Every variable holds one reference that is either *owned* or |
| 5 | 5 | //! *borrowed*: |
| 6 | | −//! - function parameters are owned; |
| 7 | | −//! - a `let` owns its result; |
| 6 | +//! - function parameters are owned, unless borrow inference ([`borrow`]) |
| 7 | +//! made them borrowed: then the caller keeps the reference; |
| 8 | +//! - a `let` owns its result, except a field projection, which borrows from |
| 9 | +//! the value it reads (a `dup` follows when it must be owned); |
| 8 | 10 | //! - inside a nested block, variables still needed after the block are |
| 9 | 11 | //! borrowed by it. |
| 10 | 12 | //! |
| @@ -14,128 +16,186 @@ |
| 14 | 16 | //! constructors and closures, and returned values. A use there consumes |
| 15 | 17 | //! the variable if it is its last use, and takes a `dup` otherwise. |
| 16 | 18 | //! - **Borrowed positions** leave it owned: the base of a field access, the |
| 17 | | −//! value a `switch` inspects, arguments of externs and primitives, and |
| 18 | | −//! the capability of an operation. Externs and the runtime never take |
| 19 | | −//! ownership of their arguments; results are always owned. |
| 19 | +//! value a `switch` inspects, arguments of externs and primitives, the |
| 20 | +//! capability of an operation, and borrowed parameters of direct calls. |
| 21 | +//! Externs and the runtime never take ownership of their arguments; |
| 22 | +//! results are always owned. |
| 20 | 23 | //! - **Dead variables** are dropped as early as possible: on entry to each |
| 21 | 24 | //! expression, every owned variable it does not mention is dropped. So |
| 22 | 25 | //! drops happen at the start of the branch or the `let` where the |
| 23 | 26 | //! variable is no longer needed, and before a tail call, never after it. |
| 24 | 27 | //! |
| 25 | | −//! Not yet done (M5 follow-ups): borrow inference for parameters, reuse |
| 26 | | −//! (FBIP) and drop specialisation. |
| 28 | +//! [`verify`] checks the result independently. |
| 29 | + |
| 30 | +mod borrow; |
| 31 | +mod verify; |
| 27 | 32 | |
| 28 | 33 | use std::collections::{BTreeSet, HashMap}; |
| 29 | 34 | |
| 30 | | −use tilc_core::ir::{Atom, Expr, Program, Value, VarId}; |
| 35 | +use tilc_core::ir::{Atom, Expr, FnDecl, FnId, Program, Value, VarId}; |
| 36 | + |
| 37 | +pub use verify::verify; |
| 31 | 38 | |
| 32 | 39 | type Set = BTreeSet<VarId>; |
| 33 | 40 | |
| 34 | | −/// Insert `dup` and `drop` into every function of `program`. |
| 41 | +/// Decide which parameters are borrowed, then insert `dup` and `drop` into |
| 42 | +/// every function of `program`. |
| 35 | 43 | pub fn insert_rc(program: &mut Program) { |
| 36 | | − for f in &mut program.fns { |
| 37 | | − let owned: Set = f.params.iter().copied().collect(); |
| 38 | | − let body = std::mem::replace(&mut f.body, Expr::Return(Atom::Unit)); |
| 39 | | − f.body = expr(body, owned, &Set::new()); |
| 44 | + borrow::infer(program); |
| 45 | + let bodies: Vec<Expr> = program |
| 46 | + .fns |
| 47 | + .iter_mut() |
| 48 | + .map(|f| std::mem::replace(&mut f.body, Expr::Return(Atom::Unit))) |
| 49 | + .collect(); |
| 50 | + for (id, body) in bodies.into_iter().enumerate() { |
| 51 | + let f = &program.fns[id]; |
| 52 | + let borrowed: Set = f.borrowed.iter().map(|i| f.params[*i]).collect(); |
| 53 | + let owned: Set = f |
| 54 | + .params |
| 55 | + .iter() |
| 56 | + .filter(|p| !borrowed.contains(p)) |
| 57 | + .copied() |
| 58 | + .collect(); |
| 59 | + let body = Rc { fns: &program.fns }.expr(body, owned, &borrowed); |
| 60 | + program.fns[id].body = body; |
| 40 | 61 | } |
| 41 | 62 | } |
| 42 | 63 | |
| 43 | | −/// Rewrite `e`, which owns `owned` and may borrow `borrowed`. |
| 44 | | −fn expr(e: Expr, owned: Set, borrowed: &Set) -> Expr { |
| 45 | | − let free = free_expr(&e); |
| 46 | | − let (owned, dead): (Set, Set) = owned.into_iter().partition(|v| free.contains(v)); |
| 47 | | − let body = match e { |
| 48 | | − Expr::Return(a) => { |
| 49 | | − let mut out = Expr::Return(a.clone()); |
| 50 | | − if let Atom::Var(x) = a |
| 51 | | − && !owned.contains(&x) |
| 52 | | − { |
| 53 | | − out = Expr::Dup(x, Box::new(out)); |
| 54 | | − } |
| 55 | | − out |
| 56 | | − } |
| 57 | | − Expr::Let(v, value, rest) => { |
| 58 | | − let mut live_after = free_expr(&rest); |
| 59 | | − live_after.remove(&v); |
| 60 | | − match *value { |
| 61 | | − Value::Block(inner) => { |
| 62 | | − let inner_free = free_expr(&inner); |
| 63 | | − let given: Set = owned |
| 64 | | − .iter() |
| 65 | | − .filter(|x| inner_free.contains(x) && !live_after.contains(x)) |
| 66 | | − .copied() |
| 67 | | − .collect(); |
| 68 | | − let mut inner_borrowed = borrowed.clone(); |
| 69 | | − inner_borrowed.extend(owned.iter().filter(|x| live_after.contains(x))); |
| 70 | | − let inner = expr(*inner, given.clone(), &inner_borrowed); |
| 71 | | − let mut after: Set = owned.difference(&given).copied().collect(); |
| 72 | | − after.insert(v); |
| 73 | | − Expr::Let( |
| 74 | | − v, |
| 75 | | − Box::new(Value::Block(Box::new(inner))), |
| 76 | | − Box::new(expr(*rest, after, borrowed)), |
| 77 | | − ) |
| 64 | +/// Dup/drop insertion, with the functions' signatures (borrowed parameters). |
| 65 | +struct Rc<'a> { |
| 66 | + fns: &'a [FnDecl], |
| 67 | +} |
| 68 | + |
| 69 | +impl Rc<'_> { |
| 70 | + /// Rewrite `e`, which owns `owned` and may borrow `borrowed`. |
| 71 | + fn expr(&self, e: Expr, owned: Set, borrowed: &Set) -> Expr { |
| 72 | + let free = free_expr(&e); |
| 73 | + let (owned, dead): (Set, Set) = owned.into_iter().partition(|v| free.contains(v)); |
| 74 | + let body = match e { |
| 75 | + Expr::Return(a) => { |
| 76 | + let mut out = Expr::Return(a.clone()); |
| 77 | + if let Atom::Var(x) = a |
| 78 | + && !owned.contains(&x) |
| 79 | + { |
| 80 | + out = Expr::Dup(x, Box::new(out)); |
| 78 | 81 | } |
| 79 | | − value => { |
| 80 | | − let (owned_uses, borrowed_uses) = uses(&value); |
| 81 | | − let mut remaining: HashMap<VarId, usize> = HashMap::new(); |
| 82 | | − for x in &owned_uses { |
| 83 | | − *remaining.entry(*x).or_default() += 1; |
| 82 | + out |
| 83 | + } |
| 84 | + Expr::Let(v, value, rest) => { |
| 85 | + let mut live_after = free_expr(&rest); |
| 86 | + let used = live_after.remove(&v); |
| 87 | + match *value { |
| 88 | + Value::Block(inner) => { |
| 89 | + let inner_free = free_expr(&inner); |
| 90 | + let given: Set = owned |
| 91 | + .iter() |
| 92 | + .filter(|x| inner_free.contains(x) && !live_after.contains(x)) |
| 93 | + .copied() |
| 94 | + .collect(); |
| 95 | + let mut inner_borrowed = borrowed.clone(); |
| 96 | + inner_borrowed.extend(owned.iter().filter(|x| live_after.contains(x))); |
| 97 | + let inner = self.expr(*inner, given.clone(), &inner_borrowed); |
| 98 | + let mut after: Set = owned.difference(&given).copied().collect(); |
| 99 | + after.insert(v); |
| 100 | + Expr::Let( |
| 101 | + v, |
| 102 | + Box::new(Value::Block(Box::new(inner))), |
| 103 | + Box::new(self.expr(*rest, after, borrowed)), |
| 104 | + ) |
| 84 | 105 | } |
| 85 | | − let mut dups = Vec::new(); |
| 86 | | − let mut after = owned.clone(); |
| 87 | | − for x in owned_uses { |
| 88 | | − let n = remaining.get_mut(&x).expect("counted"); |
| 89 | | − *n -= 1; |
| 90 | | − let last = *n == 0; |
| 91 | | − if owned.contains(&x) |
| 92 | | − && last |
| 93 | | − && !live_after.contains(&x) |
| 94 | | − && !borrowed_uses.contains(&x) |
| 95 | | − { |
| 96 | | − after.remove(&x); |
| 106 | + // A projection borrows from the value it reads. It is |
| 107 | + // owned (dup'd) only when that value is owned: the |
| 108 | + // value may be released before the projection's last |
| 109 | + // use. A projection of a borrowed value is borrowed for |
| 110 | + // as long as that value is. |
| 111 | + Value::Field(base, i) => { |
| 112 | + let value = Box::new(Value::Field(base.clone(), i)); |
| 113 | + let from_owned = matches!(base, Atom::Var(x) if owned.contains(&x)); |
| 114 | + if from_owned { |
| 115 | + let mut after = owned; |
| 116 | + if used { |
| 117 | + after.insert(v); |
| 118 | + let rest = self.expr(*rest, after, borrowed); |
| 119 | + Expr::Let(v, value, Box::new(Expr::Dup(v, Box::new(rest)))) |
| 120 | + } else { |
| 121 | + Expr::Let(v, value, Box::new(self.expr(*rest, after, borrowed))) |
| 122 | + } |
| 97 | 123 | } else { |
| 98 | | − dups.push(x); |
| 124 | + let mut rest_borrowed = borrowed.clone(); |
| 125 | + rest_borrowed.insert(v); |
| 126 | + Expr::Let(v, value, Box::new(self.expr(*rest, owned, &rest_borrowed))) |
| 99 | 127 | } |
| 100 | 128 | } |
| 101 | | − after.insert(v); |
| 102 | | − let mut out = |
| 103 | | − Expr::Let(v, Box::new(value), Box::new(expr(*rest, after, borrowed))); |
| 104 | | − for x in dups.into_iter().rev() { |
| 105 | | − out = Expr::Dup(x, Box::new(out)); |
| 129 | + value => { |
| 130 | + let (owned_uses, borrowed_uses) = uses(&value, self.fns); |
| 131 | + let mut remaining: HashMap<VarId, usize> = HashMap::new(); |
| 132 | + for x in &owned_uses { |
| 133 | + *remaining.entry(*x).or_default() += 1; |
| 134 | + } |
| 135 | + let mut dups = Vec::new(); |
| 136 | + let mut after = owned.clone(); |
| 137 | + for x in owned_uses { |
| 138 | + let n = remaining.get_mut(&x).expect("counted"); |
| 139 | + *n -= 1; |
| 140 | + let last = *n == 0; |
| 141 | + if owned.contains(&x) |
| 142 | + && last |
| 143 | + && !live_after.contains(&x) |
| 144 | + && !borrowed_uses.contains(&x) |
| 145 | + { |
| 146 | + after.remove(&x); |
| 147 | + } else { |
| 148 | + dups.push(x); |
| 149 | + } |
| 150 | + } |
| 151 | + after.insert(v); |
| 152 | + let mut out = Expr::Let( |
| 153 | + v, |
| 154 | + Box::new(value), |
| 155 | + Box::new(self.expr(*rest, after, borrowed)), |
| 156 | + ); |
| 157 | + for x in dups.into_iter().rev() { |
| 158 | + out = Expr::Dup(x, Box::new(out)); |
| 159 | + } |
| 160 | + out |
| 106 | 161 | } |
| 107 | | − out |
| 108 | 162 | } |
| 109 | 163 | } |
| 110 | | − } |
| 111 | | − Expr::Switch { on, cases, default } => Expr::Switch { |
| 112 | | − on, |
| 113 | | − cases: cases |
| 114 | | − .into_iter() |
| 115 | | − .map(|(t, b)| (t, expr(b, owned.clone(), borrowed))) |
| 116 | | − .collect(), |
| 117 | | − default: default.map(|d| Box::new(expr(*d, owned.clone(), borrowed))), |
| 118 | | − }, |
| 119 | | − Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 120 | | − on, |
| 121 | | − cases: cases |
| 122 | | − .into_iter() |
| 123 | | − .map(|(l, b)| (l, expr(b, owned.clone(), borrowed))) |
| 124 | | − .collect(), |
| 125 | | − default: Box::new(expr(*default, owned.clone(), borrowed)), |
| 126 | | − }, |
| 127 | | − e @ Expr::Panic(_) => e, |
| 128 | | − // Not present before this pass. |
| 129 | | − e @ (Expr::Dup(..) | Expr::Drop(..)) => e, |
| 130 | | − }; |
| 131 | | − dead.into_iter() |
| 132 | | − .rev() |
| 133 | | − .fold(body, |e, x| Expr::Drop(x, Box::new(e))) |
| 164 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 165 | + on, |
| 166 | + cases: cases |
| 167 | + .into_iter() |
| 168 | + .map(|(t, b)| (t, self.expr(b, owned.clone(), borrowed))) |
| 169 | + .collect(), |
| 170 | + default: default.map(|d| Box::new(self.expr(*d, owned.clone(), borrowed))), |
| 171 | + }, |
| 172 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 173 | + on, |
| 174 | + cases: cases |
| 175 | + .into_iter() |
| 176 | + .map(|(l, b)| (l, self.expr(b, owned.clone(), borrowed))) |
| 177 | + .collect(), |
| 178 | + default: Box::new(self.expr(*default, owned.clone(), borrowed)), |
| 179 | + }, |
| 180 | + e @ Expr::Panic(_) => e, |
| 181 | + // Not present before this pass. |
| 182 | + e @ (Expr::Dup(..) | Expr::Drop(..)) => e, |
| 183 | + }; |
| 184 | + dead.into_iter() |
| 185 | + .rev() |
| 186 | + .fold(body, |e, x| Expr::Drop(x, Box::new(e))) |
| 187 | + } |
| 134 | 188 | } |
| 135 | 189 | |
| 136 | 190 | /// Variables a value uses in owned positions (in order, with repeats) and |
| 137 | | −/// in borrowed positions. |
| 138 | | −pub fn uses(value: &Value) -> (Vec<VarId>, BTreeSet<VarId>) { |
| 191 | +/// in borrowed positions, given the functions' signatures. |
| 192 | +pub fn uses(value: &Value, fns: &[FnDecl]) -> (Vec<VarId>, BTreeSet<VarId>) { |
| 193 | + uses_with(value, |f, i| fns[f as usize].borrowed.contains(&i)) |
| 194 | +} |
| 195 | + |
| 196 | +/// [`uses`], where `borrows(f, i)` tells whether function `f` borrows its |
| 197 | +/// parameter `i`. |
| 198 | +fn uses_with(value: &Value, borrows: impl Fn(FnId, usize) -> bool) -> (Vec<VarId>, Set) { |
| 139 | 199 | let vars = |atoms: &[Atom]| -> Vec<VarId> { |
| 140 | 200 | atoms |
| 141 | 201 | .iter() |
| @@ -153,10 +213,23 @@ pub fn uses(value: &Value) -> (Vec<VarId>, BTreeSet<VarId>) { |
| 153 | 213 | owned.extend(vars(args)); |
| 154 | 214 | (owned, Set::new()) |
| 155 | 215 | } |
| 156 | | − Value::CallFn(_, args) |
| 157 | | − | Value::Construct { args, .. } |
| 158 | | − | Value::Tuple(args) |
| 159 | | − | Value::Closure(_, args) => (vars(args), Set::new()), |
| 216 | + Value::CallFn(f, args) => { |
| 217 | + let mut owned = Vec::new(); |
| 218 | + let mut borrowed = Set::new(); |
| 219 | + for (i, a) in args.iter().enumerate() { |
| 220 | + if let Atom::Var(v) = a { |
| 221 | + if borrows(*f, i) { |
| 222 | + borrowed.insert(*v); |
| 223 | + } else { |
| 224 | + owned.push(*v); |
| 225 | + } |
| 226 | + } |
| 227 | + } |
| 228 | + (owned, borrowed) |
| 229 | + } |
| 230 | + Value::Construct { args, .. } | Value::Tuple(args) | Value::Closure(_, args) => { |
| 231 | + (vars(args), Set::new()) |
| 232 | + } |
| 160 | 233 | Value::CallExtern(_, args) | Value::Prim(_, args) => { |
| 161 | 234 | (Vec::new(), vars(args).into_iter().collect()) |
| 162 | 235 | } |
| @@ -197,8 +270,9 @@ fn free_into(e: &Expr, out: &mut Set) { |
| 197 | 270 | out.extend(inner); |
| 198 | 271 | match &**value { |
| 199 | 272 | Value::Block(b) => free_into(b, out), |
| 273 | + // Which positions are owned does not matter here. |
| 200 | 274 | value => { |
| 201 | | − let (owned, borrowed) = uses(value); |
| 275 | + let (owned, borrowed) = uses_with(value, |_, _| false); |
| 202 | 276 | out.extend(owned); |
| 203 | 277 | out.extend(borrowed); |
| 204 | 278 | } |
| @@ -228,124 +302,3 @@ fn free_into(e: &Expr, out: &mut Set) { |
| 228 | 302 | } |
| 229 | 303 | } |
| 230 | 304 | } |
| 231 | | − |
| 232 | | −/// Check that a program's reference counting is balanced: along every |
| 233 | | −/// path, each reference (a parameter, a `let` result, or a `dup`) is used |
| 234 | | −/// by exactly one owned position, `return` or `drop`, and borrowed |
| 235 | | −/// positions only use variables holding a reference. Paths ending in a |
| 236 | | −/// panic are exempt (the actor stops). An independent check of |
| 237 | | −/// [`insert_rc`], used by the tests. |
| 238 | | −pub fn verify(program: &Program) -> Result<(), String> { |
| 239 | | − for f in &program.fns { |
| 240 | | − let counts: HashMap<VarId, i32> = f.params.iter().map(|p| (*p, 1)).collect(); |
| 241 | | − let check = || -> Result<(), String> { |
| 242 | | − for end in verify_expr(&f.body, counts.clone())? { |
| 243 | | − if let Some((v, n)) = end.iter().find(|(_, n)| **n != 0) { |
| 244 | | − return Err(format!("v{v} has {n} references left at a return")); |
| 245 | | − } |
| 246 | | − } |
| 247 | | − Ok(()) |
| 248 | | − }; |
| 249 | | − check().map_err(|e| format!("{}: {e}", f.name))?; |
| 250 | | − } |
| 251 | | − Ok(()) |
| 252 | | −} |
| 253 | | − |
| 254 | | −type Counts = HashMap<VarId, i32>; |
| 255 | | − |
| 256 | | −/// The reference counts at each `return` reached from `e` (after the |
| 257 | | −/// returned value is consumed); panicking paths contribute nothing. |
| 258 | | −fn verify_expr(e: &Expr, mut counts: Counts) -> Result<Vec<Counts>, String> { |
| 259 | | − let take = |counts: &mut Counts, v: VarId| -> Result<(), String> { |
| 260 | | − match counts.get_mut(&v) { |
| 261 | | − Some(n) if *n > 0 => { |
| 262 | | − *n -= 1; |
| 263 | | − Ok(()) |
| 264 | | − } |
| 265 | | − _ => Err(format!("v{v} is used without holding a reference")), |
| 266 | | − } |
| 267 | | − }; |
| 268 | | − let held = |counts: &Counts, v: VarId| -> Result<(), String> { |
| 269 | | − match counts.get(&v) { |
| 270 | | − Some(n) if *n > 0 => Ok(()), |
| 271 | | − _ => Err(format!("v{v} is borrowed without holding a reference")), |
| 272 | | − } |
| 273 | | − }; |
| 274 | | − match e { |
| 275 | | − Expr::Return(a) => { |
| 276 | | − if let Atom::Var(v) = a { |
| 277 | | − take(&mut counts, *v)?; |
| 278 | | − } |
| 279 | | − Ok(vec![counts]) |
| 280 | | − } |
| 281 | | − Expr::Panic(_) => Ok(Vec::new()), |
| 282 | | − Expr::Dup(v, rest) => { |
| 283 | | − held(&counts, *v)?; |
| 284 | | − *counts.get_mut(v).expect("held") += 1; |
| 285 | | − verify_expr(rest, counts) |
| 286 | | − } |
| 287 | | − Expr::Drop(v, rest) => { |
| 288 | | − take(&mut counts, *v)?; |
| 289 | | − verify_expr(rest, counts) |
| 290 | | − } |
| 291 | | − Expr::Let(v, value, rest) => { |
| 292 | | − let afters = match &**value { |
| 293 | | − Value::Block(inner) => verify_expr(inner, counts)?, |
| 294 | | − value => { |
| 295 | | − let (owned, borrowed) = uses(value); |
| 296 | | − for b in &borrowed { |
| 297 | | − held(&counts, *b)?; |
| 298 | | − } |
| 299 | | − for o in owned { |
| 300 | | − take(&mut counts, o)?; |
| 301 | | − } |
| 302 | | − vec![counts] |
| 303 | | − } |
| 304 | | − }; |
| 305 | | − // A block's branches must agree on what they leave behind. |
| 306 | | − let mut first: Option<Counts> = None; |
| 307 | | − for mut c in afters { |
| 308 | | − c.retain(|_, n| *n != 0); |
| 309 | | − match &first { |
| 310 | | − None => first = Some(c), |
| 311 | | − Some(f) if *f == c => {} |
| 312 | | − Some(_) => { |
| 313 | | − return Err("the branches of a block leave different references".into()); |
| 314 | | − } |
| 315 | | − } |
| 316 | | − } |
| 317 | | − match first { |
| 318 | | − // Every branch of the block panics. |
| 319 | | − None => Ok(Vec::new()), |
| 320 | | − Some(mut c) => { |
| 321 | | − c.insert(*v, 1); |
| 322 | | − verify_expr(rest, c) |
| 323 | | − } |
| 324 | | − } |
| 325 | | − } |
| 326 | | − Expr::Switch { on, cases, default } => { |
| 327 | | − if let Atom::Var(v) = on { |
| 328 | | − held(&counts, *v)?; |
| 329 | | − } |
| 330 | | − let mut out = Vec::new(); |
| 331 | | − for (_, b) in cases { |
| 332 | | − out.extend(verify_expr(b, counts.clone())?); |
| 333 | | − } |
| 334 | | − if let Some(d) = default { |
| 335 | | − out.extend(verify_expr(d, counts)?); |
| 336 | | − } |
| 337 | | − Ok(out) |
| 338 | | − } |
| 339 | | − Expr::SwitchLit { on, cases, default } => { |
| 340 | | − if let Atom::Var(v) = on { |
| 341 | | − held(&counts, *v)?; |
| 342 | | − } |
| 343 | | − let mut out = Vec::new(); |
| 344 | | − for (_, b) in cases { |
| 345 | | − out.extend(verify_expr(b, counts.clone())?); |
| 346 | | − } |
| 347 | | − out.extend(verify_expr(default, counts)?); |
| 348 | | − Ok(out) |
| 349 | | − } |
| 350 | | − } |
| 351 | | −} |