veryl-analyzer 0.22.0

A modern hardware description language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
//! Peels, for the native simulator, the runtime `for` loops of an
//! `always_comb` whose `break`s are decided by values the procedure itself
//! computes, such as a step count initialised from a parameter.
//!
//! A loop with `break` converts as a runtime `for`, since unrolling it at
//! conversion would strand a runtime-conditional `break`. Only the copy of
//! the declarations the simulator builds from is rewritten; the emitted
//! SystemVerilog and the analyzer's checks keep the loop. Each iteration
//! becomes a copy of the body with the iterator as its constant, and a decided
//! `if` or `case` is replaced by the side it takes. A loop is peeled only when
//! every `break` it reaches is decided, and a peel that would leave more
//! runtime loops than it removes is dropped.
//!
//! Decisions use only the expressions `decide` evaluates, on which every
//! backend agrees. A loop whose body calls a function or holds an `if_reset`
//! is not peeled, nor one whose iterator is read outside it or written inside.

use crate::conv::Context;
use crate::ir::{
    self, ArrayLiteralItem, AssignDestination, CasePattern, Declaration, Expression, Factor,
    ForBound, ForRange, Function, Module, Op, Statement, SystemFunctionCall, SystemFunctionKind,
    TypeKind, ValueVariant, VarId, VarIndex, VarKind, VarSelect,
};
use crate::symbol::SymbolKind;
use crate::symbol_table;
use crate::value::Value;
use crate::{HashMap, HashSet};

/// Most statement and expression nodes one peeled loop may emit, counting
/// what nested bodies hold, so that the copies stay as small as a small
/// unrolled loop however large one body is.
const EMIT_LIMIT: usize = 32768;

/// Most statements peeling one loop may look at, which also bounds the
/// iterations of any loop it peels.
const VISIT_LIMIT: usize = 16384;

/// Most values known at once. An undecided branch copies them for each of
/// its sides; a value assigned while this many are known is not tracked.
const TRACKED_LIMIT: usize = 256;

/// True when `stmts` hold a `break` of the loop they are the body of.
fn has_own_break(stmts: &[Statement]) -> bool {
    stmts.iter().any(|stmt| match stmt {
        Statement::Break => true,
        Statement::If(x) => has_own_break(&x.true_side) || has_own_break(&x.false_side),
        Statement::IfReset(x) => has_own_break(&x.true_side) || has_own_break(&x.false_side),
        Statement::Case(x) => {
            has_own_break(&x.default) || x.arms.iter().any(|a| has_own_break(&a.body))
        }
        _ => false,
    })
}

fn is_break_loop(stmt: &Statement) -> bool {
    matches!(stmt, Statement::For(x) if has_own_break(&x.body))
}

/// True when an `always_comb` of `decls` holds a top-level loop with a
/// `break`, which `peel_decided_loops` may peel.
pub fn has_break_loop(decls: &[Declaration]) -> bool {
    decls
        .iter()
        .any(|decl| matches!(decl, Declaration::Comb(x) if x.statements.iter().any(is_break_loop)))
}

/// Peels the decided loops of the `always_comb` declarations in `decls`, a
/// copy of `module`'s declarations, with `context` holding `module`'s
/// variables. Returns whether any declaration changed; nothing outside a
/// peeled loop does. A testbench module is left as it is.
pub fn peel_decided_loops(
    context: &mut Context,
    module: &Module,
    decls: &mut [Declaration],
) -> bool {
    if !has_break_loop(decls) || is_test_module(module) {
        return false;
    }
    let confined = confined_iterators(decls, &module.functions);
    let mut changed = false;
    for decl in decls.iter_mut() {
        if let Declaration::Comb(x) = decl
            && x.statements.iter().any(is_break_loop)
            && let Some(stmts) = peel_procedure(context, &x.statements, &confined)
        {
            x.statements = stmts;
            changed = true;
        }
    }
    changed
}

fn is_test_module(module: &Module) -> bool {
    symbol_table::get(module.signature.symbol)
        .is_some_and(|x| matches!(&x.kind, SymbolKind::Module(x) if x.test.is_some()))
}

/// `stmts`, the body of an `always_comb`, with each top-level loop whose
/// `break`s are decided peeled; `None` when none is.
fn peel_procedure(
    context: &mut Context,
    stmts: &[Statement],
    confined: &HashSet<VarId>,
) -> Option<Vec<Statement>> {
    let mut env = KnownValues::default();
    let mut ret = Vec::with_capacity(stmts.len());
    let mut changed = false;
    for stmt in stmts {
        if let Statement::For(looped) = stmt
            && has_own_break(&looped.body)
            && let Some((copies, after)) = peel_top(context, &env, looped, confined)
        {
            env = after;
            ret.extend(copies);
            changed = true;
            continue;
        }
        apply(context, &mut env, std::slice::from_ref(stmt));
        ret.push(stmt.clone());
    }
    changed.then_some(ret)
}

fn peel_top(
    context: &mut Context,
    env: &KnownValues,
    looped: &ir::ForStatement,
    confined: &HashSet<VarId>,
) -> Option<(Vec<Statement>, KnownValues)> {
    if range_has_call(&looped.range) || stmts_have_call(&looped.body) {
        return None;
    }
    let Iterations::Known(iterations) = eval_range(context, env, &looped.range)? else {
        return None;
    };
    let mut peeler = Peeler {
        confined,
        emitted: 0,
        visited: 0,
    };
    let (copies, after) = peeler.peel(context, env.clone(), looped, iterations, &[])?;
    let before = 1 + count_loops(&looped.body);
    (count_loops(&copies) <= before).then_some((copies, after))
}

fn count_loops(stmts: &[Statement]) -> usize {
    stmts
        .iter()
        .map(|stmt| match stmt {
            Statement::For(x) => 1 + count_loops(&x.body),
            Statement::If(x) => count_loops(&x.true_side) + count_loops(&x.false_side),
            Statement::IfReset(x) => count_loops(&x.true_side) + count_loops(&x.false_side),
            Statement::Case(x) => {
                count_loops(&x.default) + x.arms.iter().map(|a| count_loops(&a.body)).sum::<usize>()
            }
            _ => 0,
        })
        .sum()
}

/// The tracked scalars, each by its value at its declared width.
#[derive(Clone, Default)]
struct KnownValues {
    vars: HashMap<VarId, u64>,
}

impl KnownValues {
    fn forget_all(&mut self) {
        self.vars.clear();
    }

    fn keep_common(&mut self, other: &KnownValues) {
        self.vars.retain(|id, v| other.vars.get(id) == Some(v));
    }
}

enum Flow {
    Continue,
    Break,
}

struct Peeler<'a> {
    confined: &'a HashSet<VarId>,
    /// Statements emitted and looked at so far for the outermost loop; what
    /// a nested peel that fails has used is not given back.
    emitted: usize,
    visited: usize,
}

impl Peeler<'_> {
    fn visit(&mut self) -> Option<()> {
        self.visited += 1;
        (self.visited <= VISIT_LIMIT).then_some(())
    }

    fn emit(&mut self, out: &mut Vec<Statement>, stmt: Statement) -> Option<()> {
        self.emitted += size(std::slice::from_ref(&stmt));
        (self.emitted <= EMIT_LIMIT).then_some(())?;
        out.push(stmt);
        Some(())
    }

    /// The straight-line copies of `looped`'s `iterations` up to the `break`
    /// they take, and what is known after them; `None` when a `break` is not
    /// decided or a limit is reached. `subs` gives the iterators of the loops
    /// around it.
    fn peel(
        &mut self,
        context: &mut Context,
        mut env: KnownValues,
        looped: &ir::ForStatement,
        iterations: Vec<usize>,
        subs: &[(VarId, Value)],
    ) -> Option<(Vec<Statement>, KnownValues)> {
        if !self.confined.contains(&looped.var_id) || !looped.var_type.array.is_empty() {
            return None;
        }
        let width = looped.var_type.total_width()?;
        if !(1..=64).contains(&width) {
            return None;
        }
        let signed = looped.var_type.signed;
        let mut subs = subs.to_vec();
        subs.push((looped.var_id, Value::new(0, width, signed)));
        let mut ret = vec![];
        for k in iterations {
            self.visit()?;
            // An iterator too narrow for its range wraps at runtime.
            if width < usize::BITS as usize && k >> width != 0 {
                return None;
            }
            let value = Value::new(k as u64, width, signed);
            subs.last_mut()?.1 = value.clone();
            env.vars.insert(looped.var_id, k as u64);
            let flow = self.specialize(context, &mut env, &looped.body, &subs, &mut ret)?;
            if let Flow::Break = flow {
                break;
            }
        }
        env.vars.remove(&looped.var_id);
        Some((ret, env))
    }

    /// Appends to `out` what `stmts` run under `env`, through `Subst` with the
    /// iterators of `subs`, replacing each decided branch by the side it
    /// takes and unrolling each loop whose range becomes known; stops at a
    /// `break`.
    ///
    /// A statement is substituted only when an iteration reaches it, so a
    /// constant index out of range in a statement after the decided `break`
    /// does not keep the loop.
    fn specialize(
        &mut self,
        context: &mut Context,
        env: &mut KnownValues,
        stmts: &[Statement],
        subs: &[(VarId, Value)],
        out: &mut Vec<Statement>,
    ) -> Option<Flow> {
        for stmt in stmts {
            self.visit()?;
            let kept = match stmt {
                Statement::Break => return Some(Flow::Break),
                Statement::If(x) => {
                    let mut cond = x.cond.clone();
                    Subst::new(context, subs).expr(&mut cond)?;
                    if let Some(taken) = eval_cond(context, env, &cond) {
                        let side = if taken { &x.true_side } else { &x.false_side };
                        if let Flow::Break = self.specialize(context, env, side, subs, out)? {
                            return Some(Flow::Break);
                        }
                        continue;
                    }
                    if has_own_break(&x.true_side) || has_own_break(&x.false_side) {
                        return None;
                    }
                    Statement::If(ir::IfStatement {
                        cond,
                        true_side: substituted(context, &x.true_side, subs)?,
                        false_side: substituted(context, &x.false_side, subs)?,
                        token: x.token,
                    })
                }
                Statement::Case(x) => {
                    let mut target = x.case_target.as_ref().clone();
                    let mut patterns: Vec<Vec<CasePattern>> =
                        x.arms.iter().map(|a| a.patterns.clone()).collect();
                    let mut subst = Subst::new(context, subs);
                    subst.expr(&mut target)?;
                    for pattern in patterns.iter_mut().flatten() {
                        subst.pattern(pattern)?;
                    }
                    let arms = patterns.iter().map(|a| a.as_slice());
                    if let Some(i) = eval_case(context, env, &target, arms) {
                        let side = x.arms.get(i).map(|a| &a.body).unwrap_or(&x.default);
                        if let Flow::Break = self.specialize(context, env, side, subs, out)? {
                            return Some(Flow::Break);
                        }
                        continue;
                    }
                    if has_own_break(std::slice::from_ref(stmt)) {
                        return None;
                    }
                    let mut arms = Vec::with_capacity(x.arms.len());
                    for (arm, patterns) in x.arms.iter().zip(patterns) {
                        arms.push(ir::CaseArm {
                            patterns,
                            body: substituted(context, &arm.body, subs)?,
                            token: arm.token,
                        });
                    }
                    Statement::Case(ir::CaseStatement {
                        arms,
                        default: substituted(context, &x.default, subs)?,
                        case_target: Box::new(target),
                        token: x.token,
                    })
                }
                Statement::For(x) => {
                    let mut range = x.range.clone();
                    Subst::new(context, subs).range(&mut range)?;
                    if let Iterations::Known(iterations) = eval_range(context, env, &range)?
                        && let Some((copies, after)) =
                            self.peel(context, env.clone(), x, iterations, subs)
                    {
                        *env = after;
                        out.extend(copies);
                        continue;
                    }
                    Statement::For(Box::new(ir::ForStatement {
                        var_id: x.var_id,
                        var_name: x.var_name,
                        var_type: x.var_type.clone(),
                        range,
                        body: substituted(context, &x.body, subs)?,
                        token: x.token,
                    }))
                }
                _ => {
                    let [kept] = substituted(context, std::slice::from_ref(stmt), subs)?
                        .try_into()
                        .ok()?;
                    kept
                }
            };
            apply(context, env, std::slice::from_ref(&kept));
            self.emit(out, kept)?;
        }
        Some(Flow::Continue)
    }
}

fn substituted(
    context: &mut Context,
    stmts: &[Statement],
    subs: &[(VarId, Value)],
) -> Option<Vec<Statement>> {
    let mut stmts = stmts.to_vec();
    Subst::new(context, subs).stmts(&mut stmts)?;
    Some(stmts)
}

/// Of the iterators of the top-level `break` loops of `decls` and of every
/// loop inside one, those that nothing outside their own loop, including a
/// function body, reads and nothing inside it writes. A later name can
/// resolve to an earlier loop's iterator, and such a read would see what the
/// runtime loop left there, which the copies do not leave.
fn confined_iterators(
    decls: &[Declaration],
    functions: &HashMap<VarId, Function>,
) -> HashSet<VarId> {
    let mut loops = vec![];
    for decl in decls {
        if let Declaration::Comb(x) = decl {
            let candidates = x.statements.iter().filter(|x| is_break_loop(x));
            collect_loops(candidates, &mut loops);
        }
    }
    let ids: HashSet<VarId> = loops.iter().map(|x| x.var_id).collect();
    // Reads of each iterator anywhere, less those inside its own loop.
    let mut outside: HashMap<VarId, usize> = HashMap::default();
    let mut count = |id: VarId| {
        if ids.contains(&id) {
            *outside.entry(id).or_default() += 1;
        }
    };
    if !decls.iter().all(|x| declaration_reads(x, &mut count)) {
        return HashSet::default();
    }
    for body in functions.values().flat_map(|x| &x.functions) {
        if !visit_reads(&body.statements, &mut count) {
            return HashSet::default();
        }
    }
    let mut confined = HashSet::default();
    for x in &loops {
        let mut inside = 0;
        let mut own = |id: VarId| inside += usize::from(id == x.var_id);
        range_reads(&x.range, &mut own);
        visit_reads(&x.body, &mut own);
        let mut written = false;
        visit_writes(&x.body, &mut |id| written |= id == x.var_id);
        if !written && outside.get(&x.var_id).copied().unwrap_or(0) == inside {
            confined.insert(x.var_id);
        }
    }
    confined
}

fn collect_loops<'a>(
    stmts: impl IntoIterator<Item = &'a Statement>,
    out: &mut Vec<&'a ir::ForStatement>,
) {
    for stmt in stmts {
        match stmt {
            Statement::For(x) => {
                out.push(x);
                collect_loops(&x.body, out);
            }
            Statement::If(x) => {
                collect_loops(&x.true_side, out);
                collect_loops(&x.false_side, out);
            }
            Statement::IfReset(x) => {
                collect_loops(&x.true_side, out);
                collect_loops(&x.false_side, out);
            }
            Statement::Case(x) => {
                collect_loops(&x.default, out);
                for arm in &x.arms {
                    collect_loops(&arm.body, out);
                }
            }
            _ => {}
        }
    }
}

fn size(stmts: &[Statement]) -> usize {
    stmts
        .iter()
        .map(|stmt| match stmt {
            Statement::Assign(x) => 1 + expr_size(&x.expr),
            Statement::If(x) => 1 + expr_size(&x.cond) + size(&x.true_side) + size(&x.false_side),
            Statement::IfReset(x) => 1 + size(&x.true_side) + size(&x.false_side),
            Statement::Case(x) => {
                1 + expr_size(&x.case_target)
                    + size(&x.default)
                    + x.arms.iter().map(|a| size(&a.body)).sum::<usize>()
            }
            Statement::For(x) => 1 + size(&x.body),
            _ => 1,
        })
        .sum()
}

fn expr_size(expr: &Expression) -> usize {
    match expr {
        Expression::Term(_) => 1,
        Expression::Unary(_, x, _) => 1 + expr_size(x),
        Expression::Binary(x, _, y, _) => 1 + expr_size(x) + expr_size(y),
        Expression::Ternary(x, y, z, _) => 1 + expr_size(x) + expr_size(y) + expr_size(z),
        Expression::Concatenation(x, _) => {
            1 + x
                .iter()
                .map(|(x, r)| expr_size(x) + r.as_ref().map_or(0, expr_size))
                .sum::<usize>()
        }
        Expression::ArrayLiteral(x, _) => 1 + x.len(),
        Expression::StructConstructor(_, x, _) => {
            1 + x.iter().map(|(_, x)| expr_size(x)).sum::<usize>()
        }
    }
}

enum Iterations {
    Known(Vec<usize>),
    /// A bound is not decided, or the range is too long to peel.
    Runtime,
}

/// The iterations of `range` when `decide` settles its bounds under `env`
/// and there are at most `VISIT_LIMIT` of them. `None`, which keeps every
/// loop around it as well, when a bound is above `i32::MAX`: the emitted
/// loop iterates an `int`.
fn eval_range(context: &mut Context, env: &KnownValues, range: &ForRange) -> Option<Iterations> {
    let mut range = range.clone();
    let (start, end) = range.bounds_mut();
    for bound in [start, end] {
        let (value, signed) = match bound {
            ForBound::Const(x, signed) => (*x as u64, *signed),
            ForBound::Expression(x) => {
                let Some(value) = decide(context, env, x) else {
                    return Some(Iterations::Runtime);
                };
                (value, x.comptime().r#type.signed)
            }
        };
        if value > i32::MAX as u64 {
            return None;
        }
        *bound = ForBound::Const(value as usize, signed);
    }
    let limit = std::mem::replace(&mut context.config.evaluate_size_limit, VISIT_LIMIT);
    let ret = range.eval_iter(context);
    context.config.evaluate_size_limit = limit;
    Some(ret.map_or(Iterations::Runtime, Iterations::Known))
}

/// Reads each iterator of the loops being peeled as its constant, as an
/// ordinary unrolled loop has them, keeping the read's type and context, and
/// folds each index and select made only of constants. A constant index or
/// select out of range, a dynamic select of an iterator and an iterator in a
/// hierarchical reference abort the peel.
struct Subst<'a> {
    context: &'a mut Context,
    subs: &'a [(VarId, Value)],
}

impl<'a> Subst<'a> {
    fn new(context: &'a mut Context, subs: &'a [(VarId, Value)]) -> Self {
        Self { context, subs }
    }

    fn value_of(&self, id: VarId) -> Option<&Value> {
        self.subs.iter().find(|x| x.0 == id).map(|x| &x.1)
    }

    fn pattern(&mut self, pattern: &mut CasePattern) -> Option<()> {
        match pattern {
            CasePattern::Eq(x) => self.expr(x),
            CasePattern::Range { lo, hi, .. } => {
                self.expr(lo)?;
                self.expr(hi)
            }
        }
    }

    fn range(&mut self, range: &mut ForRange) -> Option<()> {
        let (start, end) = range.bounds_mut();
        for bound in [start, end] {
            if let ForBound::Expression(x) = bound {
                self.expr(x)?;
            }
        }
        Some(())
    }

    fn stmts(&mut self, stmts: &mut [Statement]) -> Option<()> {
        for stmt in stmts {
            match stmt {
                Statement::Assign(x) => {
                    self.expr(&mut x.expr)?;
                    for dst in &mut x.dst {
                        self.selector(dst.id, &mut dst.index, &mut dst.select, &dst.comptime)?;
                    }
                    if let Some(dst) = &x.hier_dst
                        && self.selector_reads_iter(&dst.index, &dst.select)
                    {
                        return None;
                    }
                }
                Statement::If(x) => {
                    self.expr(&mut x.cond)?;
                    self.stmts(&mut x.true_side)?;
                    self.stmts(&mut x.false_side)?;
                }
                Statement::IfReset(x) => {
                    self.stmts(&mut x.true_side)?;
                    self.stmts(&mut x.false_side)?;
                }
                Statement::Case(x) => {
                    self.expr(&mut x.case_target)?;
                    for arm in &mut x.arms {
                        for pattern in &mut arm.patterns {
                            self.pattern(pattern)?;
                        }
                        self.stmts(&mut arm.body)?;
                    }
                    self.stmts(&mut x.default)?;
                }
                Statement::For(x) => {
                    self.range(&mut x.range)?;
                    self.stmts(&mut x.body)?;
                }
                Statement::Break | Statement::Null | Statement::Unsupported(_) => {}
                Statement::SystemFunctionCall(_)
                | Statement::FunctionCall(_)
                | Statement::TbMethodCall(_) => return None,
            }
        }
        Some(())
    }

    /// The constant a read of an iterator, whole or a constant select of
    /// it, stands for.
    fn const_read(&mut self, factor: &Factor) -> Option<Factor> {
        let Factor::Variable(id, index, select, comptime) = factor else {
            return None;
        };
        let mut value = self.value_of(*id)?.clone();
        if !index.0.is_empty() || comptime.part_select.is_some() {
            return None;
        }
        if !select.is_empty() {
            // The select is evaluated from what the analyzer holds, which a
            // variable it reads is not.
            let mut reads = false;
            selector_reads(index, select, &mut |_| reads = true);
            if reads {
                return None;
            }
            let r#type = self.context.variables.get(id)?.r#type.clone();
            let (beg, end) = select.eval_value(self.context, &r#type, false)?;
            value = value.select(beg, end);
        }
        if comptime.r#type.total_width() != Some(value.width()) {
            return None;
        }
        value.set_signed(comptime.r#type.signed);
        let mut comptime = comptime.clone();
        comptime.value = ValueVariant::Numeric(value);
        comptime.is_const = true;
        Some(Factor::Value(comptime))
    }

    /// `expr` as a constant when it reads no variable and evaluates free of
    /// X and Z, as conversion folds an index of an unrolled loop.
    fn folded(&mut self, expr: &Expression) -> Option<Expression> {
        let mut reads = false;
        expr_reads(expr, &mut |_| reads = true);
        if reads || expr.comptime().is_const {
            return None;
        }
        let value = expr.eval_value(self.context)?;
        if value.is_xz() {
            return None;
        }
        let mut comptime = expr.comptime().clone();
        comptime.value = ValueVariant::Numeric(value);
        comptime.is_const = true;
        Some(Expression::Term(Box::new(Factor::Value(comptime))))
    }

    /// Substitutes inside the index and the select of `id` and folds each
    /// of their expressions that becomes constant.
    fn selector(
        &mut self,
        id: VarId,
        index: &mut VarIndex,
        select: &mut VarSelect,
        comptime: &ir::Comptime,
    ) -> Option<()> {
        let mut changed = false;
        for x in index
            .0
            .iter_mut()
            .chain(select.0.iter_mut())
            .chain(select.1.as_mut().map(|x| &mut x.1))
        {
            if !self.reads_iter(x) {
                continue;
            }
            self.expr(x)?;
            if let Some(c) = self.folded(x) {
                *x = c;
            }
            changed = true;
        }
        if changed {
            self.check_in_range(id, index, select, comptime)?;
        }
        Some(())
    }

    fn reads_iter(&self, expr: &Expression) -> bool {
        let mut ret = false;
        expr_reads(expr, &mut |id| ret |= self.value_of(id).is_some());
        ret
    }

    fn selector_reads_iter(&self, index: &VarIndex, select: &VarSelect) -> bool {
        let mut ret = false;
        selector_reads(index, select, &mut |id| ret |= self.value_of(id).is_some());
        ret
    }

    fn expr(&mut self, expr: &mut Expression) -> Option<()> {
        match expr {
            Expression::Term(x) => {
                if let Factor::Variable(id, ..) = x.as_ref()
                    && self.value_of(*id).is_some()
                {
                    **x = self.const_read(x)?;
                    return Some(());
                }
                self.factor(x)
            }
            Expression::Unary(_, x, _) => self.expr(x),
            Expression::Binary(x, _, y, _) => {
                self.expr(x)?;
                self.expr(y)
            }
            Expression::Ternary(x, y, z, _) => {
                self.expr(x)?;
                self.expr(y)?;
                self.expr(z)
            }
            Expression::Concatenation(items, _) => {
                for (x, rep) in items {
                    self.expr(x)?;
                    if let Some(rep) = rep {
                        self.expr(rep)?;
                    }
                }
                Some(())
            }
            Expression::ArrayLiteral(items, _) => {
                for item in items {
                    match item {
                        ArrayLiteralItem::Value(x, rep) => {
                            self.expr(x)?;
                            if let Some(rep) = rep {
                                self.expr(rep)?;
                            }
                        }
                        ArrayLiteralItem::Defaul(x) => self.expr(x)?,
                    }
                }
                Some(())
            }
            Expression::StructConstructor(_, items, _) => {
                for (_, x) in items {
                    self.expr(x)?;
                }
                Some(())
            }
        }
    }

    fn factor(&mut self, factor: &mut Factor) -> Option<()> {
        match factor {
            Factor::Variable(id, index, select, comptime) => {
                let comptime = comptime.clone();
                self.selector(*id, index, select, &comptime)
            }
            Factor::HierVariable(x) => {
                (!self.selector_reads_iter(&x.index, &x.select)).then_some(())
            }
            Factor::SystemFunctionCall(x) => match &mut x.kind {
                SystemFunctionKind::Signed(input) | SystemFunctionKind::Unsigned(input) => {
                    self.expr(&mut input.0)
                }
                _ => Some(()),
            },
            Factor::FunctionCall(_) => None,
            Factor::Value(_) | Factor::Anonymous(_) | Factor::Unknown(_) => Some(()),
        }
    }

    /// `None` when a constant index or select of `id` is out of range, or
    /// is into a struct, a multi-dimensional vector or a stepped range, whose
    /// bounds are not checked here. A dynamic one is left to run as it does.
    fn check_in_range(
        &mut self,
        id: VarId,
        index: &VarIndex,
        select: &VarSelect,
        comptime: &ir::Comptime,
    ) -> Option<()> {
        let r#type = self.context.variables.get(&id)?.r#type.clone();
        if index.is_const() {
            if index.0.len() > r#type.array.dims() {
                return None;
            }
            for (x, dim) in index.0.iter().zip(r#type.array.iter()) {
                if self.usize_of(x)? >= (*dim)? {
                    return None;
                }
            }
        }
        if !select.is_empty() && select.is_const_with_range() {
            if comptime.part_select.is_some()
                || r#type.is_struct_union()
                || r#type.width().dims() > 1
                || select.0.len() > 1
            {
                return None;
            }
            let width = r#type.total_width()?;
            let x = self.usize_of(&select.0[0])?;
            let (hi, lo) = match &select.1 {
                None => (x, x),
                Some((ir::VarSelectOp::Colon, y)) => (x, self.usize_of(y)?),
                Some((ir::VarSelectOp::PlusColon, y)) => {
                    (x.checked_add(self.usize_of(y)?)?.checked_sub(1)?, x)
                }
                Some((ir::VarSelectOp::MinusColon, y)) => {
                    (x, x.checked_add(1)?.checked_sub(self.usize_of(y)?)?)
                }
                Some((ir::VarSelectOp::Step, _)) => return None,
            };
            if hi < lo || hi >= width {
                return None;
            }
        }
        Some(())
    }

    fn usize_of(&mut self, expr: &Expression) -> Option<usize> {
        let value = expr.eval_value(self.context)?;
        if value.is_xz() {
            return None;
        }
        value.to_usize()
    }
}

fn mask(width: usize) -> u64 {
    if width >= 64 {
        u64::MAX
    } else {
        (1 << width) - 1
    }
}

/// Where an operand sits, which decides whether its sign can matter.
#[derive(Clone, Copy, PartialEq)]
enum Parent {
    /// A whole condition, assignment source or bound, or a self-determined
    /// operand.
    Root,
    /// An operand of a comparison.
    Compare,
    /// An operand of arithmetic, bitwise logic or a shift.
    Arith,
}

/// The value of `expr` at the width its context evaluates it at, when it is
/// a decision this pass may take: integers of at most 64 bits free of X and
/// Z, read from constants, iterator values and tracked locals, combined by
/// `+ - * / %`, comparisons, `&& || !`, `& | ^ ~` and shifts by a constant
/// amount within the width. Every operation must evaluate unsigned, and an
/// operand whose type or context is signed must be non-negative, so that
/// sign and zero extension agree; a signed context is accepted only where
/// nothing is computed in it, a comparison of two operands or the whole
/// expression. A division or modulo by zero, and anything else, is left
/// undecided.
fn decide(context: &Context, env: &KnownValues, expr: &Expression) -> Option<u64> {
    decide_at(context, env, expr, Parent::Root)
}

fn decide_at(
    context: &Context,
    env: &KnownValues,
    expr: &Expression,
    parent: Parent,
) -> Option<u64> {
    let comptime = expr.comptime();
    let ctx = &comptime.expr_context;
    if let Expression::Term(x) = expr {
        let (value, width) = leaf(context, env, x)?;
        // A whole expression folded at conversion carries no context.
        let ctx_width = if ctx.width == 0 && parent == Parent::Root {
            width
        } else {
            ctx.width
        };
        let signed = comptime.r#type.signed || ctx.signed;
        if width > ctx_width || ctx_width > 64 || (signed && value >> (width - 1) != 0) {
            return None;
        }
        if ctx.signed && parent == Parent::Arith {
            return None;
        }
        return Some(value);
    }
    if ctx.width == 0
        || ctx.width > 64
        || ctx.signed
        || comptime.r#type.signed
        || comptime
            .r#type
            .total_width()
            .is_none_or(|x| x == 0 || x > 64)
    {
        return None;
    }
    let width = ctx.width;
    match expr {
        Expression::Unary(Op::LogicNot, x, _) => {
            Some(u64::from(decide_at(context, env, x, Parent::Root)? == 0))
        }
        Expression::Unary(Op::BitNot, x, _) => {
            Some(!decide_at(context, env, x, Parent::Arith)? & mask(width))
        }
        Expression::Binary(x, op, y, _) => {
            let operand = |e: &Expression, p: Parent| decide_at(context, env, e, p);
            let value = match op {
                Op::LogicAnd | Op::LogicOr => {
                    let x = operand(x, Parent::Root)? != 0;
                    let y = operand(y, Parent::Root)? != 0;
                    u64::from(if *op == Op::LogicAnd { x && y } else { x || y })
                }
                Op::Eq | Op::Ne | Op::Less | Op::LessEq | Op::Greater | Op::GreaterEq => {
                    let x = operand(x, Parent::Compare)?;
                    let y = operand(y, Parent::Compare)?;
                    u64::from(match op {
                        Op::Eq => x == y,
                        Op::Ne => x != y,
                        Op::Less => x < y,
                        Op::LessEq => x <= y,
                        Op::Greater => x > y,
                        _ => x >= y,
                    })
                }
                Op::LogicShiftL | Op::LogicShiftR => {
                    let Expression::Term(amount) = y.as_ref() else {
                        return None;
                    };
                    if matches!(amount.as_ref(), Factor::Variable(id, ..) if env.vars.contains_key(id))
                    {
                        return None;
                    }
                    let amount = operand(y, Parent::Root)?;
                    if amount >= width as u64 {
                        return None;
                    }
                    let x = operand(x, Parent::Arith)?;
                    if *op == Op::LogicShiftL {
                        x << amount
                    } else {
                        x >> amount
                    }
                }
                Op::Add
                | Op::Sub
                | Op::Mul
                | Op::Div
                | Op::Rem
                | Op::BitAnd
                | Op::BitOr
                | Op::BitXor => {
                    let x = operand(x, Parent::Arith)?;
                    let y = operand(y, Parent::Arith)?;
                    match op {
                        Op::Add => x.wrapping_add(y),
                        Op::Sub => x.wrapping_sub(y),
                        Op::Mul => x.wrapping_mul(y),
                        Op::Div => x.checked_div(y)?,
                        Op::Rem => x.checked_rem(y)?,
                        Op::BitAnd => x & y,
                        Op::BitOr => x | y,
                        _ => x ^ y,
                    }
                }
                _ => return None,
            };
            Some(value & mask(width))
        }
        _ => None,
    }
}

/// A leaf's value and declared width: a literal, a scalar constant, or a
/// tracked scalar.
fn leaf(context: &Context, env: &KnownValues, factor: &Factor) -> Option<(u64, usize)> {
    let (comptime, value) = match factor {
        Factor::Value(x) => (x, x.get_value().ok()?.clone()),
        Factor::Variable(id, index, select, x)
            if index.0.is_empty() && select.is_empty() && x.part_select.is_none() =>
        {
            if let Some(value) = env.vars.get(id) {
                let width = x.r#type.total_width()?;
                return integer_type(x).then_some((*value, width));
            }
            let var = context.variables.get(id)?;
            if !x.is_const
                || !matches!(var.kind, VarKind::Param | VarKind::Const)
                || !var.r#type.array.is_empty()
            {
                return None;
            }
            let [value] = var.value.as_slice() else {
                return None;
            };
            (x, value.clone())
        }
        _ => return None,
    };
    let width = comptime.r#type.total_width()?;
    if !integer_type(comptime) || value.is_xz() || value.width() > 64 {
        return None;
    }
    // A value narrower than its type, from a fold at conversion, extends by
    // its own sign, so it is taken only where that cannot matter.
    let own = value.width();
    let signed = value.signed() || comptime.r#type.signed || comptime.expr_context.signed;
    let value = value.to_u64()?;
    let negative = own > 0 && value >> (own - 1) != 0;
    (own > 0 && value & !mask(width) == 0 && !(signed && negative)).then_some((value, width))
}

fn integer_type(comptime: &ir::Comptime) -> bool {
    let r#type = &comptime.r#type;
    matches!(
        r#type.kind,
        TypeKind::Bit | TypeKind::Logic | TypeKind::Enum(_)
    ) && r#type.array.is_empty()
        && r#type.total_width().is_some_and(|x| (1..=64).contains(&x))
}

fn eval_cond(context: &Context, env: &KnownValues, cond: &Expression) -> Option<bool> {
    Some(decide(context, env, cond)? != 0)
}

/// Index of the arm a `case` takes (`arms.len()` for `default`), when the
/// target is a whole unsigned constant or tracked scalar and every pattern
/// tried before the match is a constant `decide` settles. Every value is then
/// compared as the non-negative integer it is, whatever width the comparison
/// runs at.
fn eval_case<'a>(
    context: &Context,
    env: &KnownValues,
    target: &Expression,
    arms: impl IntoIterator<Item = &'a [CasePattern]>,
) -> Option<usize> {
    let constant = |x: &Expression| {
        let Expression::Term(factor) = x else {
            return None;
        };
        if matches!(factor.as_ref(), Factor::Variable(id, ..) if env.vars.contains_key(id)) {
            return None;
        }
        decide(context, env, x)
    };
    if target.comptime().r#type.signed || !matches!(target, Expression::Term(_)) {
        return None;
    }
    let target = decide(context, env, target)?;
    let mut count = 0;
    for (i, patterns) in arms.into_iter().enumerate() {
        count = i + 1;
        for pattern in patterns {
            let hit = match pattern {
                CasePattern::Eq(x) => constant(x)? == target,
                CasePattern::Range { lo, hi, inclusive } => {
                    let lo = constant(lo)?;
                    let hi = constant(hi)?;
                    lo <= target
                        && if *inclusive {
                            target <= hi
                        } else {
                            target < hi
                        }
                }
            };
            if hit {
                return Some(i);
            }
        }
    }
    Some(count)
}

/// The value a whole-scalar blocking assignment leaves, or `None` when the
/// destination is not such a scalar or the value is not decided.
fn assigned_value(
    context: &Context,
    env: &KnownValues,
    x: &ir::AssignStatement,
) -> Option<(VarId, u64)> {
    let [dst] = x.dst.as_slice() else {
        return None;
    };
    if !dst.index.0.is_empty() || !dst.select.is_empty() || dst.comptime.part_select.is_some() {
        return None;
    }
    let var = context.variables.get(&dst.id)?;
    let width = var.r#type.total_width()?;
    if var.value.len() != 1
        || !var.r#type.array.is_empty()
        || !matches!(
            var.r#type.kind,
            TypeKind::Bit | TypeKind::Logic | TypeKind::Enum(_)
        )
        || !(1..=64).contains(&width)
    {
        return None;
    }
    Some((dst.id, decide(context, env, &x.expr)? & mask(width)))
}

/// Advances `env` over `stmts` as the procedure runs them. Returns false
/// when a `break` ends the list.
fn apply(context: &mut Context, env: &mut KnownValues, stmts: &[Statement]) -> bool {
    for stmt in stmts {
        match stmt {
            Statement::Assign(x) => {
                if expr_has_call(&x.expr) || x.dst.iter().any(dst_has_call) {
                    env.forget_all();
                    continue;
                }
                let known = assigned_value(context, env, x);
                for dst in &x.dst {
                    env.vars.remove(&dst.id);
                }
                if let Some((id, value)) = known
                    && env.vars.len() < TRACKED_LIMIT
                {
                    env.vars.insert(id, value);
                }
            }
            Statement::If(x) => {
                if expr_has_call(&x.cond) {
                    env.forget_all();
                    continue;
                }
                match eval_cond(context, env, &x.cond) {
                    Some(true) => {
                        if !apply(context, env, &x.true_side) {
                            return false;
                        }
                    }
                    Some(false) => {
                        if !apply(context, env, &x.false_side) {
                            return false;
                        }
                    }
                    None => {
                        let mut other = env.clone();
                        apply(context, &mut other, &x.true_side);
                        apply(context, env, &x.false_side);
                        env.keep_common(&other);
                    }
                }
            }
            Statement::Case(x) => {
                if expr_has_call(&x.case_target)
                    || x.arms
                        .iter()
                        .any(|a| a.patterns.iter().any(pattern_has_call))
                {
                    env.forget_all();
                    continue;
                }
                let arms = x.arms.iter().map(|a| a.patterns.as_slice());
                match eval_case(context, env, &x.case_target, arms) {
                    Some(i) => {
                        let body = x.arms.get(i).map(|a| &a.body).unwrap_or(&x.default);
                        if !apply(context, env, body) {
                            return false;
                        }
                    }
                    None => {
                        let before = env.clone();
                        apply(context, env, &x.default);
                        for arm in &x.arms {
                            let mut other = before.clone();
                            apply(context, &mut other, &arm.body);
                            env.keep_common(&other);
                        }
                    }
                }
            }
            Statement::For(x) => {
                if range_has_call(&x.range) || stmts_have_call(&x.body) {
                    env.forget_all();
                } else {
                    forget_writes(env, &x.body);
                }
            }
            Statement::Break => return false,
            Statement::Null => {}
            Statement::IfReset(_)
            | Statement::SystemFunctionCall(_)
            | Statement::FunctionCall(_)
            | Statement::TbMethodCall(_)
            | Statement::Unsupported(_) => env.forget_all(),
        }
    }
    true
}

fn expr_has_call(expr: &Expression) -> bool {
    match expr {
        Expression::Term(x) => factor_has_call(x),
        Expression::Unary(_, x, _) => expr_has_call(x),
        Expression::Binary(x, _, y, _) => expr_has_call(x) || expr_has_call(y),
        Expression::Ternary(x, y, z, _) => expr_has_call(x) || expr_has_call(y) || expr_has_call(z),
        Expression::Concatenation(items, _) => items
            .iter()
            .any(|(x, rep)| expr_has_call(x) || rep.as_ref().is_some_and(expr_has_call)),
        Expression::ArrayLiteral(items, _) => items.iter().any(|x| match x {
            ArrayLiteralItem::Value(x, rep) => {
                expr_has_call(x) || rep.as_deref().is_some_and(expr_has_call)
            }
            ArrayLiteralItem::Defaul(x) => expr_has_call(x),
        }),
        Expression::StructConstructor(_, items, _) => items.iter().any(|(_, x)| expr_has_call(x)),
    }
}

fn factor_has_call(factor: &Factor) -> bool {
    match factor {
        Factor::Variable(_, index, select, _) => {
            index.0.iter().chain(select.0.iter()).any(expr_has_call)
                || select.1.as_ref().is_some_and(|(_, x)| expr_has_call(x))
        }
        Factor::HierVariable(x) => {
            x.index.0.iter().chain(x.select.0.iter()).any(expr_has_call)
                || x.select.1.as_ref().is_some_and(|(_, x)| expr_has_call(x))
        }
        Factor::FunctionCall(_) => true,
        Factor::SystemFunctionCall(x) => match &x.kind {
            SystemFunctionKind::Signed(input) | SystemFunctionKind::Unsigned(input) => {
                expr_has_call(&input.0)
            }
            // Its arguments are not inspected, so only a folded one is known
            // free.
            _ => !x.comptime.is_const,
        },
        Factor::Value(_) | Factor::Anonymous(_) | Factor::Unknown(_) => false,
    }
}

fn dst_has_call(dst: &AssignDestination) -> bool {
    dst.index
        .0
        .iter()
        .chain(dst.select.0.iter())
        .any(expr_has_call)
        || dst.select.1.as_ref().is_some_and(|(_, x)| expr_has_call(x))
}

fn pattern_has_call(pattern: &CasePattern) -> bool {
    match pattern {
        CasePattern::Eq(x) => expr_has_call(x),
        CasePattern::Range { lo, hi, .. } => expr_has_call(lo) || expr_has_call(hi),
    }
}

fn range_has_call(range: &ForRange) -> bool {
    let (start, end) = range.bounds();
    [start, end]
        .into_iter()
        .any(|x| matches!(x, ForBound::Expression(x) if expr_has_call(x)))
}

/// True when anything in `stmts`, at any depth, calls a function, which may
/// write its output arguments behind any value known here, or is a statement
/// nothing is known across.
fn stmts_have_call(stmts: &[Statement]) -> bool {
    stmts.iter().any(|stmt| match stmt {
        Statement::Assign(x) => {
            expr_has_call(&x.expr) || x.dst.iter().any(dst_has_call) || x.hier_dst.is_some()
        }
        Statement::If(x) => {
            expr_has_call(&x.cond)
                || stmts_have_call(&x.true_side)
                || stmts_have_call(&x.false_side)
        }
        Statement::Case(x) => {
            expr_has_call(&x.case_target)
                || x.arms
                    .iter()
                    .any(|a| a.patterns.iter().any(pattern_has_call) || stmts_have_call(&a.body))
                || stmts_have_call(&x.default)
        }
        Statement::For(x) => range_has_call(&x.range) || stmts_have_call(&x.body),
        Statement::IfReset(_)
        | Statement::FunctionCall(_)
        | Statement::SystemFunctionCall(_)
        | Statement::TbMethodCall(_)
        | Statement::Unsupported(_) => true,
        Statement::Break | Statement::Null => false,
    })
}

/// Forgets every variable `stmts`, which hold no call, may write.
fn forget_writes(env: &mut KnownValues, stmts: &[Statement]) {
    visit_writes(stmts, &mut |id| {
        env.vars.remove(&id);
    });
}

/// Calls `f` with each variable an assignment in `stmts` writes. A call's
/// outputs are not seen.
fn visit_writes(stmts: &[Statement], f: &mut impl FnMut(VarId)) {
    for stmt in stmts {
        match stmt {
            Statement::Assign(x) => {
                for dst in &x.dst {
                    f(dst.id);
                }
            }
            Statement::If(x) => {
                visit_writes(&x.true_side, f);
                visit_writes(&x.false_side, f);
            }
            Statement::IfReset(x) => {
                visit_writes(&x.true_side, f);
                visit_writes(&x.false_side, f);
            }
            Statement::Case(x) => {
                visit_writes(&x.default, f);
                for arm in &x.arms {
                    visit_writes(&arm.body, f);
                }
            }
            Statement::For(x) => visit_writes(&x.body, f),
            _ => {}
        }
    }
}

/// Calls `f` with each variable `stmts` read, once per read; false when
/// they hold a testbench method call, whose arguments are not seen.
fn visit_reads(stmts: &[Statement], f: &mut impl FnMut(VarId)) -> bool {
    for stmt in stmts {
        let seen = match stmt {
            Statement::Assign(x) => {
                expr_reads(&x.expr, f);
                for dst in &x.dst {
                    selector_reads(&dst.index, &dst.select, f);
                }
                if let Some(dst) = &x.hier_dst {
                    selector_reads(&dst.index, &dst.select, f);
                }
                true
            }
            Statement::If(x) => {
                expr_reads(&x.cond, f);
                visit_reads(&x.true_side, f) && visit_reads(&x.false_side, f)
            }
            Statement::IfReset(x) => visit_reads(&x.true_side, f) && visit_reads(&x.false_side, f),
            Statement::Case(x) => {
                expr_reads(&x.case_target, f);
                for pattern in x.arms.iter().flat_map(|a| &a.patterns) {
                    match pattern {
                        CasePattern::Eq(x) => expr_reads(x, f),
                        CasePattern::Range { lo, hi, .. } => {
                            expr_reads(lo, f);
                            expr_reads(hi, f);
                        }
                    }
                }
                x.arms.iter().all(|a| visit_reads(&a.body, f)) && visit_reads(&x.default, f)
            }
            Statement::For(x) => {
                range_reads(&x.range, f);
                visit_reads(&x.body, f)
            }
            Statement::FunctionCall(x) => {
                call_reads(x, f);
                true
            }
            Statement::SystemFunctionCall(x) => {
                system_reads(x, f);
                true
            }
            Statement::TbMethodCall(_) => false,
            Statement::Break | Statement::Null | Statement::Unsupported(_) => true,
        };
        if !seen {
            return false;
        }
    }
    true
}

/// Calls `f` with each variable `decl` reads, once per read; false when it
/// holds a testbench method call, whose arguments are not seen.
fn declaration_reads(decl: &Declaration, f: &mut impl FnMut(VarId)) -> bool {
    match decl {
        Declaration::Comb(x) => visit_reads(&x.statements, f),
        Declaration::Ff(x) => {
            f(x.clock.id);
            selector_reads(&x.clock.index, &x.clock.select, f);
            if let Some(reset) = &x.reset {
                f(reset.id);
                selector_reads(&reset.index, &reset.select, f);
            }
            visit_reads(&x.statements, f)
        }
        Declaration::Inst(x) => {
            for x in x.inputs.iter().flat_map(|x| &x.exprs) {
                expr_reads(x, f);
            }
            for dst in x.outputs.iter().flat_map(|x| &x.dst) {
                selector_reads(&dst.index, &dst.select, f);
            }
            for x in &x.interface_bindings {
                f(x.parent);
                selector_reads(&x.index, &x.select, f);
            }
            true
        }
        Declaration::External(x) => {
            for x in &x.connects {
                expr_reads(&x.expr, f);
                if let Some(dst) = &x.output {
                    selector_reads(&dst.index, &dst.select, f);
                }
            }
            true
        }
        Declaration::Initial(x) => visit_reads(&x.statements, f),
        Declaration::Final(x) => visit_reads(&x.statements, f),
        Declaration::Unsupported(_) | Declaration::Null => true,
    }
}

fn range_reads(range: &ForRange, f: &mut impl FnMut(VarId)) {
    let (start, end) = range.bounds();
    for bound in [start, end] {
        if let ForBound::Expression(x) = bound {
            expr_reads(x, f);
        }
    }
}

fn selector_reads(index: &VarIndex, select: &VarSelect, f: &mut impl FnMut(VarId)) {
    for x in index.0.iter().chain(&select.0) {
        expr_reads(x, f);
    }
    if let Some((_, x)) = &select.1 {
        expr_reads(x, f);
    }
}

fn call_reads(call: &ir::FunctionCall, f: &mut impl FnMut(VarId)) {
    for x in call.inputs.values() {
        expr_reads(x, f);
    }
    for dst in call.outputs.values().flatten() {
        selector_reads(&dst.index, &dst.select, f);
    }
}

fn system_reads(call: &SystemFunctionCall, f: &mut impl FnMut(VarId)) {
    match &call.kind {
        SystemFunctionKind::Bits(x)
        | SystemFunctionKind::Clog2(x)
        | SystemFunctionKind::Onehot(x)
        | SystemFunctionKind::Signed(x)
        | SystemFunctionKind::Unsigned(x) => expr_reads(&x.0, f),
        SystemFunctionKind::Size(x, y) => {
            expr_reads(&x.0, f);
            if let Some(y) = y {
                expr_reads(&y.0, f);
            }
        }
        SystemFunctionKind::Readmemh(x, out) => {
            expr_reads(&x.0, f);
            for dst in out.local() {
                selector_reads(&dst.index, &dst.select, f);
            }
        }
        SystemFunctionKind::Display(args) | SystemFunctionKind::Write(args) => {
            for x in args {
                expr_reads(&x.0, f);
            }
        }
        SystemFunctionKind::Assert { cond, args, .. } => {
            expr_reads(&cond.0, f);
            for x in args {
                expr_reads(&x.0, f);
            }
        }
        SystemFunctionKind::Finish => {}
    }
}

fn expr_reads(expr: &Expression, f: &mut impl FnMut(VarId)) {
    match expr {
        Expression::Term(x) => match x.as_ref() {
            Factor::Variable(id, index, select, _) => {
                f(*id);
                selector_reads(index, select, f);
            }
            Factor::HierVariable(x) => selector_reads(&x.index, &x.select, f),
            Factor::FunctionCall(x) => call_reads(x, f),
            Factor::SystemFunctionCall(x) => system_reads(x, f),
            Factor::Value(_) | Factor::Anonymous(_) | Factor::Unknown(_) => {}
        },
        Expression::Unary(_, x, _) => expr_reads(x, f),
        Expression::Binary(x, _, y, _) => {
            expr_reads(x, f);
            expr_reads(y, f);
        }
        Expression::Ternary(x, y, z, _) => {
            expr_reads(x, f);
            expr_reads(y, f);
            expr_reads(z, f);
        }
        Expression::Concatenation(items, _) => {
            for (x, rep) in items {
                expr_reads(x, f);
                if let Some(rep) = rep {
                    expr_reads(rep, f);
                }
            }
        }
        Expression::ArrayLiteral(items, _) => {
            for item in items {
                match item {
                    ArrayLiteralItem::Value(x, rep) => {
                        expr_reads(x, f);
                        if let Some(rep) = rep {
                            expr_reads(rep, f);
                        }
                    }
                    ArrayLiteralItem::Defaul(x) => expr_reads(x, f),
                }
            }
        }
        Expression::StructConstructor(_, items, _) => {
            for (_, x) in items {
                expr_reads(x, f);
            }
        }
    }
}