logicaffeine_compile/analysis/
liveness.rs1use std::collections::{HashMap, HashSet};
2
3use logicaffeine_base::Symbol;
4use logicaffeine_language::ast::stmt::Pattern;
5use logicaffeine_language::ast::{Expr, Stmt};
6
7use crate::optimize::Mentions;
8
9pub struct LivenessResult {
22 functions: HashMap<Symbol, FunctionLiveness>,
23 by_stmt: HashMap<usize, HashSet<Symbol>>,
25}
26
27pub struct FunctionLiveness {
29 pub live_after: Vec<HashSet<Symbol>>,
31}
32
33impl LivenessResult {
34 pub fn analyze(stmts: &[Stmt<'_>]) -> Self {
39 let mut functions = HashMap::new();
40 let mut by_stmt = HashMap::new();
41 let none_pinned = HashSet::new();
42 for stmt in stmts {
43 if let Stmt::FunctionDef { name, body, .. } = stmt {
44 functions.insert(*name, analyze_body(body, &none_pinned, &mut by_stmt));
45 }
46 }
47 let reached: HashSet<Symbol> = stmts
50 .iter()
51 .filter_map(|s| match s {
52 Stmt::FunctionDef { body, .. } => {
53 Some(Mentions::of_block(body).symbols().collect::<Vec<_>>())
54 }
55 _ => None,
56 })
57 .flatten()
58 .collect();
59 analyze_body(stmts, &reached, &mut by_stmt);
60 Self { functions, by_stmt }
61 }
62
63 pub fn after(&self, stmt: &Stmt<'_>) -> Option<&HashSet<Symbol>> {
66 self.by_stmt.get(&stmt_key(stmt))
67 }
68
69 pub fn into_statement_table(self) -> HashMap<usize, HashSet<Symbol>> {
71 self.by_stmt
72 }
73
74 pub fn is_live_after(&self, fn_sym: Symbol, stmt_idx: usize, var: Symbol) -> bool {
80 self.functions
81 .get(&fn_sym)
82 .and_then(|fl| fl.live_after.get(stmt_idx))
83 .map(|s| s.contains(&var))
84 .unwrap_or(false)
85 }
86
87 pub fn live_after(&self, fn_sym: Symbol, stmt_idx: usize) -> &HashSet<Symbol> {
92 static EMPTY: std::sync::OnceLock<HashSet<Symbol>> = std::sync::OnceLock::new();
93 self.functions
94 .get(&fn_sym)
95 .and_then(|fl| fl.live_after.get(stmt_idx))
96 .unwrap_or_else(|| EMPTY.get_or_init(HashSet::new))
97 }
98}
99
100pub fn stmt_key(stmt: &Stmt<'_>) -> usize {
102 stmt as *const Stmt<'_> as *const () as usize
103}
104
105struct Walk<'r> {
112 every: HashSet<Symbol>,
114 pinned: &'r HashSet<Symbol>,
116 break_exit: Option<HashSet<Symbol>>,
118 return_exit: Option<HashSet<Symbol>>,
120 by_stmt: &'r mut HashMap<usize, HashSet<Symbol>>,
121}
122
123fn analyze_body(
124 body: &[Stmt<'_>],
125 pinned: &HashSet<Symbol>,
126 by_stmt: &mut HashMap<usize, HashSet<Symbol>>,
127) -> FunctionLiveness {
128 let mut walk = Walk {
129 every: Mentions::of_block(body).symbols().collect(),
130 pinned,
131 break_exit: None,
132 return_exit: None,
133 by_stmt,
134 };
135 let n = body.len();
136 let mut live_after = vec![HashSet::<Symbol>::new(); n];
137 let mut current: HashSet<Symbol> = pinned.clone();
138
139 for i in (0..n).rev() {
140 if is_terminator(&body[i]) {
141 live_after[i] = pinned.clone();
144 walk.record(&body[i], &live_after[i]);
145 current = walk.gen_stmt(&body[i]);
146 } else {
147 live_after[i] = current.clone();
148 current = walk.live_before_stmt(&body[i], ¤t);
149 }
150 }
151
152 FunctionLiveness { live_after }
153}
154
155fn is_terminator(stmt: &Stmt<'_>) -> bool {
156 matches!(stmt, Stmt::Return { .. })
157}
158
159impl Walk<'_> {
160 fn record(&mut self, stmt: &Stmt<'_>, live_out: &HashSet<Symbol>) {
163 let mut live = live_out.clone();
164 live.extend(self.pinned.iter().copied());
165 self.by_stmt.insert(stmt_key(stmt), live);
166 }
167
168 fn gen_stmt(&self, stmt: &Stmt<'_>) -> HashSet<Symbol> {
170 let mut out = self.pinned.clone();
171 if let Stmt::Return { value: Some(v) } = stmt {
172 self.gen_expr(v, &mut out);
173 }
174 out
175 }
176
177 fn live_before_stmt(&mut self, stmt: &Stmt<'_>, live_out: &HashSet<Symbol>) -> HashSet<Symbol> {
180 if matches!(stmt, Stmt::Break) {
183 let exit = self.break_exit.clone().unwrap_or_else(|| self.every.clone());
184 self.record(stmt, &exit);
185 return exit;
186 }
187 if let (Stmt::Return { value }, Some(exit)) = (stmt, self.return_exit.clone()) {
189 self.record(stmt, &exit);
190 let mut before = exit;
191 if let Some(value) = value {
192 self.gen_expr(value, &mut before);
193 }
194 return before;
195 }
196 self.record(stmt, live_out);
197 match stmt {
198 Stmt::Return { .. } => self.gen_stmt(stmt),
199
200 Stmt::Let { var, value, .. } => {
201 let mut result = live_out.clone();
202 result.remove(var);
203 self.gen_expr(value, &mut result);
204 result
205 }
206
207 Stmt::Set { target, value } => {
208 let mut result = live_out.clone();
209 result.remove(target);
210 self.gen_expr(value, &mut result);
211 result
212 }
213
214 Stmt::Call { function, args } => {
215 let mut result = live_out.clone();
216 result.insert(*function);
218 for a in args.iter() {
219 self.gen_expr(a, &mut result);
220 }
221 result
222 }
223
224 Stmt::Push { value, collection } => {
225 let mut result = live_out.clone();
226 self.gen_expr(value, &mut result);
227 self.gen_expr(collection, &mut result);
228 result
229 }
230
231 Stmt::Pop { collection, into } => {
232 let mut result = live_out.clone();
233 if let Some(v) = into {
234 result.remove(v);
235 }
236 self.gen_expr(collection, &mut result);
237 result
238 }
239
240 Stmt::Add { value, collection } | Stmt::Remove { value, collection } => {
241 let mut result = live_out.clone();
242 self.gen_expr(value, &mut result);
243 self.gen_expr(collection, &mut result);
244 result
245 }
246
247 Stmt::SetIndex {
248 collection,
249 index,
250 value,
251 } => {
252 let mut result = live_out.clone();
253 self.gen_expr(collection, &mut result);
254 self.gen_expr(index, &mut result);
255 self.gen_expr(value, &mut result);
256 result
257 }
258
259 Stmt::SetField { object, value, .. } => {
260 let mut result = live_out.clone();
261 self.gen_expr(object, &mut result);
262 self.gen_expr(value, &mut result);
263 result
264 }
265
266 Stmt::If {
267 cond,
268 then_block,
269 else_block,
270 } => {
271 let then_lb = self.live_before_block(then_block, live_out);
272 let else_lb = match else_block {
273 Some(b) => self.live_before_block(b, live_out),
274 None => live_out.clone(),
275 };
276 let mut result = HashSet::new();
277 self.gen_expr(cond, &mut result);
278 result.extend(then_lb);
279 result.extend(else_lb);
280 result
281 }
282
283 Stmt::While {
284 cond,
285 body,
286 decreasing,
287 } => {
288 let mut loop_live: HashSet<Symbol> = live_out.clone();
290 self.gen_expr(cond, &mut loop_live);
291 if let Some(d) = decreasing {
292 self.gen_expr(d, &mut loop_live);
293 }
294 let enclosing = self.break_exit.replace(live_out.clone());
295 loop {
296 let body_before = self.live_before_block(body, &loop_live);
297 let mut new_live = live_out.clone();
298 self.gen_expr(cond, &mut new_live);
299 if let Some(d) = decreasing {
300 self.gen_expr(d, &mut new_live);
301 }
302 new_live.extend(body_before);
303 if new_live == loop_live {
304 break;
305 }
306 loop_live = new_live;
307 }
308 self.break_exit = enclosing;
309 loop_live
310 }
311
312 Stmt::Repeat {
313 pattern,
314 iterable,
315 body,
316 } => {
317 let pattern_syms: HashSet<Symbol> = match pattern {
320 Pattern::Identifier(s) => [*s].into_iter().collect(),
321 Pattern::Tuple(syms) => syms.iter().copied().collect(),
322 };
323 let mut loop_live: HashSet<Symbol> = live_out.clone();
324 let enclosing = self.break_exit.replace(live_out.clone());
325 loop {
326 let body_before = self.live_before_block(body, &loop_live);
327 let mut new_live = live_out.clone();
328 new_live.extend(
329 body_before
330 .into_iter()
331 .filter(|s| !pattern_syms.contains(s)),
332 );
333 if new_live == loop_live {
334 break;
335 }
336 loop_live = new_live;
337 }
338 self.break_exit = enclosing;
339 let mut result = loop_live;
340 self.gen_expr(iterable, &mut result);
341 result
342 }
343
344 Stmt::Inspect { target, arms, .. } => {
345 let mut result = HashSet::new();
346 for arm in arms.iter() {
347 let arm_lb = self.live_before_block(arm.body, live_out);
348 result.extend(arm_lb);
349 }
350 self.gen_expr(target, &mut result);
351 result
352 }
353
354 Stmt::Zone { body, .. } => {
355 let enclosing_break = self.break_exit.replace(live_out.clone());
356 let enclosing_return = self.return_exit.replace(live_out.clone());
357 let before = self.live_before_block(body, live_out);
358 self.break_exit = enclosing_break;
359 self.return_exit = enclosing_return;
360 before
361 }
362
363 _ => {
367 let touched = Mentions::of_stmt(stmt);
368 let mut result = live_out.clone();
369 result.extend(touched.symbols());
370 if touched.is_opaque() {
371 result.extend(self.every.iter().copied());
372 }
373 result
374 }
375 }
376 }
377
378 fn live_before_block(
380 &mut self,
381 stmts: &[Stmt<'_>],
382 live_out: &HashSet<Symbol>,
383 ) -> HashSet<Symbol> {
384 let mut current = live_out.clone();
385 for stmt in stmts.iter().rev() {
386 if is_terminator(stmt) && self.return_exit.is_none() {
387 let after = self.pinned.clone();
388 self.record(stmt, &after);
389 current = self.gen_stmt(stmt);
390 } else {
391 current = self.live_before_stmt(stmt, ¤t);
392 }
393 }
394 current
395 }
396
397 fn gen_expr(&self, expr: &Expr<'_>, out: &mut HashSet<Symbol>) {
401 let touched = Mentions::of_expr(expr);
402 out.extend(touched.symbols());
403 if touched.is_opaque() {
404 out.extend(self.every.iter().copied());
405 }
406 }
407}
408
409#[cfg(test)]
410#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/analysis/liveness/tests.rs"]
411mod tests;