1use serde::{Deserialize, Serialize};
10
11#[derive(Clone, Debug, Default)]
14pub struct Cfg {
15 pub succ: Vec<Vec<(usize, String)>>,
16}
17
18pub fn post_dominators(cfg: &Cfg) -> Vec<Option<usize>> {
22 let n = cfg.succ.len();
23 let exit = n; let mut preds_rev: Vec<Vec<usize>> = vec![Vec::new(); n + 1]; for (a, s) in cfg.succ.iter().enumerate() {
28 if s.is_empty() {
29 preds_rev[exit].push(a);
30 }
31 for (b, _) in s {
32 preds_rev[*b].push(a);
33 }
34 }
35 let mut order = Vec::new();
36 let mut seen = vec![false; n + 1];
37 let mut stack = vec![(exit, 0usize)];
38 seen[exit] = true;
39 while let Some((v, i)) = stack.pop() {
40 if i < preds_rev[v].len() {
41 stack.push((v, i + 1));
42 let w = preds_rev[v][i];
43 if !seen[w] {
44 seen[w] = true;
45 stack.push((w, 0));
46 }
47 } else {
48 order.push(v);
49 }
50 }
51 order.reverse(); let mut rpo = vec![usize::MAX; n + 1];
53 for (k, &v) in order.iter().enumerate() {
54 rpo[v] = k;
55 }
56 let mut idom: Vec<Option<usize>> = vec![None; n + 1];
57 idom[exit] = Some(exit);
58 let intersect = |idom: &[Option<usize>], mut a: usize, mut b: usize| {
59 while a != b {
60 while rpo[a] > rpo[b] {
61 a = idom[a].unwrap();
62 }
63 while rpo[b] > rpo[a] {
64 b = idom[b].unwrap();
65 }
66 }
67 a
68 };
69 let mut changed = true;
70 while changed {
71 changed = false;
72 for &v in order.iter().skip(1) {
73 let ps: Vec<usize> = if cfg.succ[v].is_empty() {
75 vec![exit]
76 } else {
77 cfg.succ[v].iter().map(|(b, _)| *b).collect()
78 };
79 let mut new: Option<usize> = None;
80 for p in ps {
81 if idom[p].is_some() {
82 new = Some(match new {
83 None => p,
84 Some(x) => intersect(&idom, p, x),
85 });
86 }
87 }
88 if new.is_some() && idom[v] != new {
89 idom[v] = new;
90 changed = true;
91 }
92 }
93 }
94 (0..n).map(|v| idom[v].filter(|&d| d != exit)).collect()
95}
96
97#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
100pub struct Guard {
101 pub branch: usize,
102 pub label: String,
103}
104
105pub fn control_dependence(cfg: &Cfg) -> Vec<Vec<Guard>> {
107 let ipdom = post_dominators(cfg);
108 let n = cfg.succ.len();
109 let mut out: Vec<Vec<Guard>> = vec![Vec::new(); n];
110 for (a, s) in cfg.succ.iter().enumerate() {
111 if s.len() < 2 {
112 continue;
113 }
114 for (b, label) in s {
115 let mut runner = Some(*b);
118 let mut steps = 0;
119 while let Some(r) = runner {
120 if Some(r) == ipdom[a] || steps > n {
121 break;
122 }
123 let g = Guard {
124 branch: a,
125 label: label.clone(),
126 };
127 if !out[r].contains(&g) {
128 out[r].push(g);
129 }
130 runner = ipdom[r];
131 steps += 1;
132 }
133 }
134 }
135 out
136}
137
138#[derive(Clone, Debug, PartialEq, Eq)]
141pub struct NaturalLoop {
142 pub header: usize,
143 pub blocks: Vec<usize>,
145}
146
147pub fn natural_loops(cfg: &Cfg, root: usize) -> Vec<NaturalLoop> {
154 let n = cfg.succ.len();
155 if root >= n {
156 return Vec::new();
157 }
158 let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
159 for (a, s) in cfg.succ.iter().enumerate() {
160 for (b, _) in s {
161 preds[*b].push(a);
162 }
163 }
164 let mut back: Vec<(usize, usize)> = Vec::new();
166 let mut state = vec![0u8; n]; let mut stack = vec![(root, 0usize)];
168 state[root] = 1;
169 while let Some((v, i)) = stack.pop() {
170 if let Some((w, _)) = cfg.succ[v].get(i) {
171 stack.push((v, i + 1));
172 match state[*w] {
173 0 => {
174 state[*w] = 1;
175 stack.push((*w, 0));
176 }
177 1 => back.push((v, *w)),
178 _ => {}
179 }
180 } else {
181 state[v] = 2;
182 }
183 }
184 let mut loops: Vec<NaturalLoop> = Vec::new();
185 for (latch, header) in back {
186 let mut body = std::collections::BTreeSet::from([header]);
187 let mut work = vec![latch];
188 while let Some(v) = work.pop() {
189 if body.insert(v) {
190 work.extend(preds[v].iter().copied());
191 }
192 }
193 match loops.iter_mut().find(|l| l.header == header) {
194 Some(l) => {
195 let mut all: std::collections::BTreeSet<usize> = l.blocks.iter().copied().collect();
196 all.extend(body);
197 l.blocks = all.into_iter().collect();
198 }
199 None => loops.push(NaturalLoop {
200 header,
201 blocks: body.into_iter().collect(),
202 }),
203 }
204 }
205 loops.sort_by_key(|l| std::cmp::Reverse(l.blocks.len()));
206 loops
207}
208
209#[derive(Clone, Debug, Serialize, Deserialize)]
211pub struct PdgLoop {
212 pub header: usize,
213 pub line: usize,
214 pub per_item_of: String,
217 pub nodes: Vec<usize>,
219 pub exits: Vec<Guard>,
221 pub inside: Option<usize>,
223}
224
225#[derive(Clone, Debug, Serialize, Deserialize)]
228pub struct PdgNode {
229 pub block: usize,
230 pub line: usize,
231 pub kind: String,
233 pub callee: String,
235 pub effects: Vec<String>,
237 pub guards: Vec<Guard>,
238 #[serde(default)]
240 pub uses: Vec<usize>,
241}
242
243#[derive(Clone, Debug, Serialize, Deserialize)]
245pub struct PdgBranch {
246 pub block: usize,
247 pub line: usize,
248 pub test: String,
249 #[serde(default)]
251 pub uses: Vec<usize>,
252}
253
254#[derive(Clone, Debug, Serialize, Deserialize)]
257pub struct PdgChain {
258 pub path: String,
259 pub first: u64,
261 pub last: u64,
262 pub exits: bool,
263 pub speculate: bool,
264 pub independent: bool,
265 pub sync: bool,
267}
268
269#[derive(Clone, Debug, Serialize, Deserialize)]
271pub struct PdgJoin {
272 pub level: u64,
273 pub chains: Vec<PdgChain>,
274}
275
276#[derive(Clone, Debug, Serialize, Deserialize)]
278pub struct PdgPrefetch {
279 pub path: String,
280 pub terminates: bool,
281 pub speculate: bool,
282}
283
284#[derive(Clone, Debug, Serialize, Deserialize)]
287pub struct PdgSelect {
288 pub name: String,
290 pub line: usize,
291 pub at: usize,
293 pub futures: Vec<usize>,
295 pub handlers: Vec<usize>,
297}
298
299#[derive(Clone, Debug, Default, Serialize, Deserialize)]
301pub struct FnPdg {
302 pub path: String,
303 pub nodes: Vec<PdgNode>,
304 pub branches: Vec<PdgBranch>,
305 #[serde(default)]
307 pub joins: Vec<PdgJoin>,
308 #[serde(default)]
309 pub prefetches: Vec<PdgPrefetch>,
310 #[serde(default)]
312 pub loops: Vec<PdgLoop>,
313 #[serde(default)]
315 pub selects: Vec<PdgSelect>,
316}
317
318#[derive(Clone, Debug, Default, Serialize, Deserialize)]
319pub struct CratePdg {
320 pub crate_name: String,
321 pub functions: Vec<FnPdg>,
322 #[serde(default)]
325 pub entries: Vec<PdgEntry>,
326}
327
328#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
330pub struct PdgEntry {
331 pub framework: String,
333 pub method: String,
335 pub route: String,
337 pub handler: String,
339 pub line: usize,
341 pub registered_at: usize,
342}
343
344pub fn render_entry(e: &PdgEntry) -> String {
346 if e.framework == "main" {
347 return format!("main -> {} (line {})", e.handler, e.line);
348 }
349 let route = if e.route.is_empty() {
350 "(route not a literal)".to_string()
351 } else {
352 e.route.clone()
353 };
354 format!(
355 "{} {} {route} -> {} (line {}, registered at line {})",
356 e.framework, e.method, e.handler, e.line, e.registered_at
357 )
358}
359
360pub fn render(f: &FnPdg) -> String {
368 let blocks = |bs: &[usize]| {
369 bs.iter()
370 .map(|b| format!("b{b}"))
371 .collect::<Vec<_>>()
372 .join(", ")
373 };
374 let mut out = format!("{}\n", f.path);
375 for j in &f.joins {
376 let chains: Vec<String> = j
377 .chains
378 .iter()
379 .map(|c| {
380 let mut tags = vec![if c.first == c.last {
381 format!("statement {}", c.first)
382 } else {
383 format!("statements {}-{}", c.first, c.last)
384 }];
385 for (on, tag) in [
386 (c.exits, "may exit"),
387 (c.speculate, "speculate"),
388 (c.independent, "independent"),
389 (c.sync, "thread"),
390 ] {
391 if on {
392 tags.push(tag.into());
393 }
394 }
395 format!("{} ({})", c.path, tags.join(", "))
396 })
397 .collect();
398 out += &format!(" join {}: {}\n", j.level, chains.join(" || "));
399 }
400 for p in &f.prefetches {
401 let mut tags = Vec::new();
402 if p.terminates {
403 tags.push("the body may end the loop");
404 }
405 if p.speculate {
406 tags.push("speculate");
407 }
408 let tags = if tags.is_empty() {
409 String::new()
410 } else {
411 format!(" ({})", tags.join(", "))
412 };
413 out += &format!(" prefetch: {}{tags}\n", p.path);
414 }
415 for l in &f.loops {
416 let runs = if l.per_item_of.is_empty() {
417 "until a branch leaves it".to_string()
418 } else {
419 format!("once per item of `{}`", l.per_item_of)
420 };
421 let inside = l
422 .inside
423 .map_or(String::new(), |h| format!(", inside loop b{h}"));
424 let body = if l.nodes.is_empty() {
425 "no calls".to_string()
426 } else {
427 blocks(&l.nodes)
428 };
429 let exits: Vec<String> = l
430 .exits
431 .iter()
432 .map(|g| format!("b{} = {}", g.branch, g.label))
433 .collect();
434 let exits = if exits.is_empty() {
435 String::new()
436 } else {
437 format!("; leaves at {}", exits.join(", "))
438 };
439 out += &format!(
440 " loop b{} (line {}{inside}): runs {runs}: {body}{exits}\n",
441 l.header, l.line
442 );
443 }
444 for x in &f.selects {
445 let what = if x.name.contains("select") {
446 "the first to finish wins, the others are dropped"
447 } else {
448 "all run to the end"
449 };
450 let list = |bs: &[usize]| {
451 if bs.is_empty() {
452 "none".to_string()
453 } else {
454 blocks(bs)
455 }
456 };
457 out += &format!(
458 " {}! b{} (line {}): futures {}; handlers {}; {what}\n",
459 x.name,
460 x.at,
461 x.line,
462 list(&x.futures),
463 list(&x.handlers)
464 );
465 }
466 for n in &f.nodes {
467 let what = match n.kind.as_str() {
468 "call" => format!("call {}", n.callee),
469 k => k.to_string(),
470 };
471 let effects = if n.effects.is_empty() {
472 String::new()
473 } else {
474 format!(" [{}]", n.effects.join("; "))
475 };
476 let guards: Vec<String> = n
477 .guards
478 .iter()
479 .map(|g| {
480 let b = f.branches.iter().find(|b| b.block == g.branch);
481 match b {
482 Some(b) if !b.uses.is_empty() => format!(
483 "b{} (line {}, {} on {}) = {}",
484 g.branch,
485 b.line,
486 b.test,
487 blocks(&b.uses),
488 g.label
489 ),
490 Some(b) => format!("b{} (line {}, {}) = {}", g.branch, b.line, b.test, g.label),
491 None => format!("b{} = {}", g.branch, g.label),
492 }
493 })
494 .collect();
495 let guards = if guards.is_empty() {
496 String::new()
497 } else {
498 format!(" if {}", guards.join(" and "))
499 };
500 let uses = if n.uses.is_empty() {
501 String::new()
502 } else {
503 format!(" uses {}", blocks(&n.uses))
504 };
505 out += &format!(
506 " b{:<3} line {:<4} {what}{effects}{uses}{guards}\n",
507 n.block, n.line
508 );
509 }
510 out
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 fn cfg(edges: &[&[(usize, &str)]]) -> Cfg {
518 Cfg {
519 succ: edges
520 .iter()
521 .map(|s| s.iter().map(|(b, l)| (*b, l.to_string())).collect())
522 .collect(),
523 }
524 }
525
526 #[test]
527 fn diamond() {
528 let g = cfg(&[&[(1, "true"), (2, "false")], &[(3, "")], &[(3, "")], &[]]);
530 assert_eq!(post_dominators(&g), [Some(3), Some(3), Some(3), None]);
531 let cd = control_dependence(&g);
532 assert_eq!(
533 cd[1],
534 [Guard {
535 branch: 0,
536 label: "true".into()
537 }]
538 );
539 assert_eq!(
540 cd[2],
541 [Guard {
542 branch: 0,
543 label: "false".into()
544 }]
545 );
546 assert!(cd[0].is_empty() && cd[3].is_empty());
547 }
548
549 #[test]
550 fn early_return() {
551 let g = cfg(&[&[(2, "Ok"), (1, "Err")], &[], &[(3, "")], &[]]);
553 let cd = control_dependence(&g);
554 assert_eq!(
556 cd[2],
557 [Guard {
558 branch: 0,
559 label: "Ok".into()
560 }]
561 );
562 assert_eq!(
563 cd[3],
564 [Guard {
565 branch: 0,
566 label: "Ok".into()
567 }]
568 );
569 assert_eq!(
570 cd[1],
571 [Guard {
572 branch: 0,
573 label: "Err".into()
574 }]
575 );
576 }
577
578 #[test]
579 fn loop_body() {
580 let g = cfg(&[&[(1, "")], &[(2, "true"), (3, "false")], &[(1, "")], &[]]);
582 let cd = control_dependence(&g);
583 assert_eq!(
584 cd[2],
585 [Guard {
586 branch: 1,
587 label: "true".into()
588 }]
589 );
590 assert_eq!(
592 cd[1],
593 [Guard {
594 branch: 1,
595 label: "true".into()
596 }]
597 );
598 assert!(cd[3].is_empty());
599 }
600
601 #[test]
602 fn finds_nested_natural_loops() {
603 let cfg = Cfg {
605 succ: vec![
606 vec![(1, String::new())],
607 vec![(2, "Some".into()), (5, "None".into())],
608 vec![(3, "true".into()), (4, "false".into())],
609 vec![(2, String::new())],
610 vec![(1, String::new())],
611 vec![],
612 ],
613 };
614 let loops = natural_loops(&cfg, 0);
615 assert_eq!(
616 loops,
617 vec![
618 NaturalLoop {
619 header: 1,
620 blocks: vec![1, 2, 3, 4]
621 },
622 NaturalLoop {
623 header: 2,
624 blocks: vec![2, 3]
625 },
626 ]
627 );
628 let line = Cfg {
630 succ: vec![vec![(1, String::new())], vec![]],
631 };
632 assert!(natural_loops(&line, 0).is_empty());
633 }
634
635 #[test]
636 fn renders_loops() {
637 let f = FnPdg {
638 path: "f".into(),
639 loops: vec![
640 PdgLoop {
641 header: 4,
642 line: 10,
643 per_item_of: "std::slice::Iter<'_, u32>".into(),
644 nodes: vec![7, 9],
645 exits: vec![Guard {
646 branch: 8,
647 label: "exits".into(),
648 }],
649 inside: None,
650 },
651 PdgLoop {
652 header: 12,
653 line: 14,
654 per_item_of: String::new(),
655 nodes: vec![],
656 exits: vec![],
657 inside: Some(4),
658 },
659 ],
660 ..Default::default()
661 };
662 assert_eq!(
663 render(&f),
664 "f\n loop b4 (line 10): runs once per item of `std::slice::Iter<'_, u32>`: b7, b9; \
665 leaves at b8 = exits\n loop b12 (line 14, inside loop b4): runs until a branch \
666 leaves it: no calls\n"
667 );
668 }
669
670 #[test]
671 fn renders_joins_and_prefetches() {
672 let f = FnPdg {
673 path: "f::{closure#0}".into(),
674 joins: vec![PdgJoin {
675 level: 1,
676 chains: vec![
677 PdgChain {
678 path: "f::{closure#0}::{closure#0}".into(),
679 first: 0,
680 last: 2,
681 exits: true,
682 speculate: false,
683 independent: false,
684 sync: false,
685 },
686 PdgChain {
687 path: "f::{closure#0}::{closure#1}".into(),
688 first: 1,
689 last: 1,
690 exits: false,
691 speculate: true,
692 independent: false,
693 sync: false,
694 },
695 ],
696 }],
697 prefetches: vec![PdgPrefetch {
698 path: "f::{closure#0}::{closure#2}".into(),
699 terminates: true,
700 speculate: false,
701 }],
702 ..Default::default()
703 };
704 assert_eq!(
705 render(&f),
706 "f::{closure#0}\n join 1: f::{closure#0}::{closure#0} (statements 0-2, may exit) || \
707 f::{closure#0}::{closure#1} (statement 1, speculate)\n prefetch: \
708 f::{closure#0}::{closure#2} (the body may end the loop)\n"
709 );
710 }
711
712 #[test]
713 fn unreachable_exit_is_tolerated() {
714 let g = cfg(&[&[(0, "")], &[]]);
716 assert_eq!(post_dominators(&g), [None, None]);
717 assert!(control_dependence(&g).iter().all(Vec::is_empty));
718 }
719}