bitwright 0.32.4

Hash-consed fixed-width bit-vector expressions: exact evaluation, bit-level facts, and verified simplification.
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
//! The bitwise pass: a pure bitwise function (`& | ^ ~`, with `0` and all-ones) of at most
//! three atoms is determined by its 8-entry truth table, and is replaced by a minimum-size
//! expression for that table when that is smaller.
//!
//! Bitwise functions act on each bit position independently, so the truth table over single
//! bits (W = 1) determines the function at every width: the table is exact, not an
//! approximation. The minimum forms are found once by a breadth-first search over expression
//! sizes (an immutable cache, computed on first use) and verified exhaustively by the tests.
//!
//! *Constants.* A function of at most three atoms and some constants (masks, `(y & C) ^ C`) is,
//! on each class of bit positions where every constant is 0 or all-ones, a function of the
//! atoms alone: one truth table per class. Bit positions are independent, so the tables
//! determine the function exactly. When the classes take at most two tables, `t` on the bits of
//! a mask `M` and `u` elsewhere, it is written as the cheapest of `f_t & M` (`u` zero),
//! `f_t | ~M` (`u` all-ones), `f_u ^ M` (`t` the complement of `u`) and `f_u ^ (f_{t^u} & M)`,
//! with `f` the minimum forms (and the same with the roles swapped). The compares pass decides
//! `a == b` by the same tables: equal tables in every class, or complementary ones in some.
//!
//! *Wider regions.* Above three atoms a region is an atom of the regions over it, which can
//! hide that a function depends on few of the atoms below: a node one of whose atoms is such a
//! region is read again over up to six atoms (a 64-entry table, one `u64`), through every
//! region of at most six, and when its table depends on three atoms or fewer it is written as
//! their minimum form. So masking that cancels over more atoms comes apart:
//! `((a ^ m) & (b ^ n)) ^ ((a ^ m) & n) ^ (m & (b ^ n)) ^ (m & n)` is `a & b`. Constants are
//! atoms there, so a node of more than three atoms is read by classes first.
//!
//! *Chains.* A chain of `&` or of `|` over three operands or more is written with its operands
//! in the context's order, each once ([`sort_chain`](super::sort_chain)): one node however it
//! was parenthesized and ordered, also over more atoms than a table reads, so
//! `(a & b & … & g) ^ (g & … & b & a)` is 0. An operand beside its complement decides the chain.

use std::sync::OnceLock;

use super::{Fin, PassKind, Runner, Step, Stop, finish, worth_building};
use crate::BitVec;
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::ops::{BinOp, UnOp};

/// The truth tables of the three atoms: bit `i` is the atom's value in combination `i`, where
/// atom `k` is 1 exactly when bit `k` of `i` is.
const VARS: [u8; 3] = [0xAA, 0xCC, 0xF0];

/// The most atoms of a wide description: its table has 2^6 entries, one `u64`.
const WIDE: usize = 6;

/// The truth tables of six atoms, as [`VARS`] for three.
const WIDE_VARS: [u64; WIDE] = [
    0xAAAA_AAAA_AAAA_AAAA,
    0xCCCC_CCCC_CCCC_CCCC,
    0xF0F0_F0F0_F0F0_F0F0,
    0xFF00_FF00_FF00_FF00,
    0xFFFF_0000_FFFF_0000,
    0xFFFF_FFFF_0000_0000,
];

/// A node of a minimum-form template.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum T {
    Var(u8),
    Zero,
    Ones,
    Not(u16),
    Bin(BinOp, u16, u16),
}

/// For every truth table: a template (nodes in post-order; the last is the root) and its size
/// in operators.
pub(crate) struct MinForms {
    pub(crate) forms: Vec<(Vec<T>, u8)>,
    /// Per truth table, more templates of the same size, for renderings that share subterms
    /// with others: the first [`ALTERNATIVES`] found, then as many again each with a subterm
    /// (by table) the ones before lack.
    #[cfg_attr(not(feature = "mba"), allow(dead_code))]
    pub(crate) alts: Vec<Vec<Vec<T>>>,
}

/// The most other templates of minimum size kept per truth table in order found (and again as
/// many for new subterms).
pub(crate) const ALTERNATIVES: usize = 8;

/// The minimum forms, computed on first use.
pub(crate) fn min_forms() -> &'static MinForms {
    static FORMS: OnceLock<MinForms> = OnceLock::new();
    FORMS.get_or_init(search)
}

/// Breadth-first search over expression sizes: every function of size `c` is `~f` with
/// `size(f) = c - 1`, or `f op g` with `size(f) + size(g) = c - 1`. Ties keep the first found
/// (a fixed enumeration order), so the table is deterministic.
fn search() -> MinForms {
    // best[tt] = (template, size)
    let mut best: Vec<Option<(Vec<T>, u8)>> = vec![None; 256];
    let mut alts: Vec<Vec<Vec<T>>> = vec![Vec::new(); 256];
    // Per table, the subterm tables of its form and alternatives.
    let mut covered: Vec<Vec<u8>> = vec![Vec::new(); 256];
    best[0x00] = Some((vec![T::Zero], 0));
    best[0xFF] = Some((vec![T::Ones], 0));
    for (k, &v) in VARS.iter().enumerate() {
        best[v as usize] = Some((vec![T::Var(k as u8)], 0));
    }
    let concat = |a: &[T], b: &[T], op: BinOp| -> Vec<T> {
        let off = a.len() as u16;
        let mut out = a.to_vec();
        out.extend(b.iter().map(|t| match *t {
            T::Not(x) => T::Not(x + off),
            T::Bin(o, x, y) => T::Bin(o, x + off, y + off),
            other => other,
        }));
        out.push(T::Bin(op, off - 1, out.len() as u16 - 1));
        out
    };
    let mut size = 1u8;
    while best.iter().any(Option::is_none) {
        let mut found: Vec<(usize, Vec<T>)> = Vec::new();
        for f in 0..256usize {
            let Some((tf, sf)) = &best[f] else { continue };
            if *sf + 1 == size {
                let mut t = tf.clone();
                t.push(T::Not(t.len() as u16 - 1));
                found.push((!(f as u8) as usize, t));
            }
            for (g, bg) in best.iter().enumerate().skip(f) {
                let Some((tg, sg)) = bg else { continue };
                if sf + sg + 1 != size {
                    continue;
                }
                for (op, v) in [(BinOp::And, f & g), (BinOp::Or, f | g), (BinOp::Xor, f ^ g)] {
                    found.push((v, concat(tf, tg, op)));
                }
            }
        }
        // For the tables first reached at this size, also the combinations of the operands'
        // other forms (after the forms' own, which decide the form): `(x & y) | ~(y ^ z)` from
        // `~(y ^ z)`, the other form of `~z ^ y`.
        let fresh: Vec<bool> = best.iter().map(Option::is_none).collect();
        let all = |f: usize| -> Vec<&Vec<T>> {
            best[f]
                .iter()
                .map(|(t, _)| t)
                .chain(alts[f].iter())
                .collect()
        };
        let mut more: Vec<(usize, Vec<T>)> = Vec::new();
        for f in 0..256usize {
            let Some((_, sf)) = &best[f] else { continue };
            if *sf + 1 == size && fresh[usize::from(!(f as u8))] {
                for tf in all(f).into_iter().skip(1) {
                    let mut t = tf.clone();
                    t.push(T::Not(t.len() as u16 - 1));
                    more.push((usize::from(!(f as u8)), t));
                }
            }
            for (g, bg) in best.iter().enumerate().skip(f) {
                let Some((_, sg)) = bg else { continue };
                if sf + sg + 1 != size {
                    continue;
                }
                for (op, v) in [(BinOp::And, f & g), (BinOp::Or, f | g), (BinOp::Xor, f ^ g)] {
                    if !fresh[v] {
                        continue;
                    }
                    for (i, tf) in all(f).into_iter().enumerate() {
                        for (j, tg) in all(g).into_iter().enumerate() {
                            if i > 0 || j > 0 {
                                more.push((v, concat(tf, tg, op)));
                            }
                        }
                    }
                }
            }
        }
        found.extend(more);
        // The first template found at a table's size is its form; others of that size are
        // kept as alternatives, the first few found and then those with a subterm (by table) the
        // ones kept so far lack (the forms of the level before stay as they are).
        for (v, t) in found {
            if best[v].is_none() {
                covered[v] = subtables(&t);
                best[v] = Some((t, size));
            } else if fresh[v] && alts[v].len() < 2 * ALTERNATIVES && !alts[v].contains(&t) {
                let subs = subtables(&t);
                let new = subs.iter().any(|s| !covered[v].contains(s));
                if alts[v].len() < ALTERNATIVES && best[v].as_ref().is_some_and(|(b, _)| *b != t)
                    || new
                {
                    covered[v].extend(subs);
                    alts[v].push(t);
                }
            }
        }
        size += 1;
    }
    MinForms {
        forms: best
            .into_iter()
            .map(|b| b.unwrap_or((vec![T::Zero], 0)))
            .collect(),
        alts,
    }
}

/// The truth tables of a template's operators but its root.
pub(crate) fn subtables(t: &[T]) -> Vec<u8> {
    let mut vals: Vec<u8> = Vec::with_capacity(t.len());
    for n in t {
        vals.push(match *n {
            T::Var(k) => VARS[usize::from(k)],
            T::Zero => 0,
            T::Ones => 0xFF,
            T::Not(a) => !vals[usize::from(a)],
            T::Bin(op, a, b) => {
                let (x, y) = (vals[usize::from(a)], vals[usize::from(b)]);
                match op {
                    BinOp::And => x & y,
                    BinOp::Or => x | y,
                    _ => x ^ y,
                }
            }
        });
    }
    let mut out: Vec<u8> = t
        .iter()
        .zip(&vals)
        .take(t.len().saturating_sub(1))
        .filter(|(n, _)| matches!(n, T::Not(_) | T::Bin(..)))
        .map(|(_, &v)| v)
        .collect();
    out.sort_unstable();
    out.dedup();
    out
}

/// A node's bitwise description: its atoms (sorted by index, at most three) and its truth
/// table over them; `None` for a node with more than three atoms.
pub(crate) type Info = Option<(Vec<u32>, u8)>;

/// A node's description over at most [`WIDE`] atoms, read through every bitwise region of at
/// most that many: its atoms (sorted by index) and its table over them, entries past the atoms
/// repeating (over three atoms or fewer, its first eight entries are a table as [`Info`] has).
#[derive(Clone, Copy, Debug)]
pub(crate) struct Wide {
    atoms: [u32; WIDE],
    len: u8,
    tt: u64,
}

impl Wide {
    fn atoms(&self) -> &[u32] {
        &self.atoms[..usize::from(self.len)]
    }
}

/// Drops the atoms `tt` does not depend on.
fn prune(atoms: Vec<u32>, tt: u8) -> (Vec<u32>, u8) {
    let mut keep: Vec<u32> = Vec::new();
    for (k, &a) in atoms.iter().enumerate() {
        let flip = |i: usize| (tt >> (i ^ (1 << k))) & 1 != (tt >> i) & 1;
        if (0..8).any(flip) {
            keep.push(a);
        }
    }
    let tt = remap_down(tt, &atoms, &keep);
    (keep, tt)
}

/// Re-expresses `tt` over `from` as a table over `to`, a subset the function depends on only.
fn remap_down(tt: u8, from: &[u32], to: &[u32]) -> u8 {
    let mut out = 0u8;
    for i in 0..8usize {
        // Place combination `i` of `to` into `from`, with the dropped atoms at 0.
        let mut j = 0usize;
        for (k, a) in to.iter().enumerate() {
            let p = from.iter().position(|b| b == a).unwrap_or(0);
            j |= ((i >> k) & 1) << p;
        }
        out |= ((tt >> j) & 1) << i;
    }
    // Entries for combinations beyond the atoms repeat the pattern (the table is over three
    // variables, unused ones included).
    out
}

/// Re-expresses truth table `tt` over atoms `from` as a table over `to` (a superset).
fn remap(tt: u8, from: &[u32], to: &[u32]) -> u8 {
    let pos: Vec<usize> = from
        .iter()
        .map(|a| to.iter().position(|b| b == a).unwrap_or(0))
        .collect();
    let mut out = 0u8;
    for i in 0..8usize {
        let mut j = 0usize;
        for (k, &p) in pos.iter().enumerate() {
            j |= ((i >> p) & 1) << k;
        }
        out |= ((tt >> j) & 1) << i;
    }
    out
}

fn bitwise_op(op: OpCode) -> bool {
    matches!(op, OpCode::And | OpCode::Or | OpCode::Xor | OpCode::Not)
}

/// The description of `root`, computing (iteratively) and caching those below it.
fn info_of(r: &mut Runner<'_, '_>, cx: &Context, root: u32) -> Result<Info, Stop> {
    let mut stack: Vec<(u32, bool)> = vec![(root, false)];
    while let Some((i, expanded)) = stack.pop() {
        if r.bitwise.info.contains_key(&i) {
            continue;
        }
        let node = cx.node(i);
        let leaf = |i: u32| -> Info {
            match cx.const_val(i) {
                Some(v) if v.is_zero() => Some((Vec::new(), 0x00)),
                Some(v) if v.is_ones() => Some((Vec::new(), 0xFF)),
                _ => Some((vec![i], VARS[0])),
            }
        };
        if !bitwise_op(node.op) {
            r.bitwise.info.insert(i, leaf(i));
            continue;
        }
        if !expanded {
            stack.push((i, true));
            for c in node.children() {
                if !r.bitwise.info.contains_key(&c) {
                    stack.push((c, false));
                }
            }
            continue;
        }
        r.meter.charge(Counter::PassWork, 1)?;
        let kids: Vec<Info> = node
            .children()
            .map(|c| r.bitwise.info[&c].clone())
            .collect();
        let info = if kids.iter().any(Option::is_none) {
            None
        } else {
            let mut atoms: Vec<u32> = kids
                .iter()
                .flat_map(|k| k.as_ref().map_or(Vec::new(), |k| k.0.clone()))
                .collect();
            atoms.sort_unstable();
            atoms.dedup();
            if atoms.len() > 3 {
                None
            } else {
                let t: Vec<u8> = kids
                    .iter()
                    .map(|k| {
                        let (a, tt) = k.as_ref().map_or((&[][..], 0), |k| (&k.0[..], k.1));
                        remap(tt, a, &atoms)
                    })
                    .collect();
                let tt = match node.op {
                    OpCode::Not => !t[0],
                    OpCode::And => t[0] & t[1],
                    OpCode::Or => t[0] | t[1],
                    _ => t[0] ^ t[1],
                };
                Some(prune(atoms, tt))
            }
        };
        let info = if info.is_none() {
            r.stats.passes.entry("bitwise").or_default().atomized += 1;
            leaf(i)
        } else {
            info
        };
        r.bitwise.info.insert(i, info);
    }
    Ok(r.bitwise.info[&root].clone())
}

/// Table `tt` with its variables `a < b` exchanged (a delta swap of the entries that differ).
fn swap_vars(tt: u64, a: usize, b: usize) -> u64 {
    let d = (1u32 << b) - (1u32 << a);
    // Each entry with `a` set and `b` clear, and its partner `d` above.
    let t = ((tt >> d) ^ tt) & WIDE_VARS[a] & !WIDE_VARS[b];
    tt ^ t ^ (t << d)
}

/// Re-expresses wide table `tt` over atoms `from` as a table over `to` (a superset; both sorted
/// by index): each atom's variable moves up to its place in `to`, the highest first, onto a
/// variable the table does not read.
fn remap_wide(tt: u64, from: &[u32], to: &[u32]) -> u64 {
    let mut tt = tt;
    let mut p = to.len();
    for (k, a) in from.iter().enumerate().rev() {
        while to[p - 1] != *a {
            p -= 1;
        }
        p -= 1;
        if p > k {
            tt = swap_vars(tt, k, p);
        }
    }
    tt
}

/// Drops the atoms of `atoms` (sorted by index) that table `tt` does not depend on: each kept
/// atom's variable moves down to its place among them, the lowest first.
fn prune_wide(atoms: &[u32], tt: u64) -> Wide {
    let mut out = Wide {
        atoms: [0; WIDE],
        len: 0,
        tt,
    };
    for (k, &a) in atoms.iter().enumerate() {
        // The table with atom `k` flipped.
        let (v, s) = (WIDE_VARS[k], 1u32 << k);
        if (tt & v) >> s | (tt & !v) << s == tt {
            continue;
        }
        let m = usize::from(out.len);
        if m < k {
            out.tt = swap_vars(out.tt, m, k);
        }
        out.atoms[m] = a;
        out.len += 1;
    }
    out
}

/// The wide description of node `i` as an atom (or a constant).
fn wide_leaf(cx: &Context, i: u32) -> Wide {
    let mut w = Wide {
        atoms: [0; WIDE],
        len: 0,
        tt: 0,
    };
    match cx.const_val(i) {
        Some(v) if v.is_zero() => {}
        Some(v) if v.is_ones() => w.tt = u64::MAX,
        _ => (w.atoms[0], w.len, w.tt) = (i, 1, WIDE_VARS[0]),
    }
    w
}

/// The wide description of bitwise node `i` from its operands' (`b` is `a` for `~`); over more
/// than [`WIDE`] atoms, `i` is an atom.
fn wide_op(cx: &Context, i: u32, a: Wide, b: Wide) -> Wide {
    // The operands' atoms merged, in index order.
    let mut atoms = [0u32; 2 * WIDE];
    let (mut n, mut x, mut y) = (0, a.atoms().iter().peekable(), b.atoms().iter().peekable());
    while let Some(&next) = match (x.peek(), y.peek()) {
        (Some(&&p), Some(&&q)) if p == q => {
            y.next();
            x.next()
        }
        (Some(&&p), Some(&&q)) if q < p => y.next(),
        (Some(_), _) => x.next(),
        (None, _) => y.next(),
    } {
        atoms[n] = next;
        n += 1;
    }
    if n > WIDE {
        return wide_leaf(cx, i);
    }
    let atoms = &atoms[..n];
    let (ta, tb) = (
        remap_wide(a.tt, a.atoms(), atoms),
        remap_wide(b.tt, b.atoms(), atoms),
    );
    let tt = match cx.node(i).op {
        OpCode::Not => !ta,
        OpCode::And => ta & tb,
        OpCode::Or => ta | tb,
        _ => ta ^ tb,
    };
    prune_wide(atoms, tt)
}

/// The wide description of `i` if it needs no computing: cached, an atom, or the three-atom
/// reading's where that reads no region of more than three atoms (the same atoms and function,
/// its table repeated).
fn known_wide(r: &Runner<'_, '_>, cx: &Context, i: u32) -> Option<Wide> {
    if !bitwise_op(cx.node(i).op) {
        return Some(wide_leaf(cx, i));
    }
    if let Some(&w) = r.bitwise.wide.get(&i) {
        return Some(w);
    }
    match r.bitwise.info.get(&i) {
        Some(Some((atoms, tt)))
            if atoms[..] != [i] && atoms.iter().all(|&a| !bitwise_op(cx.node(a).op)) =>
        {
            let mut w = Wide {
                atoms: [0; WIDE],
                len: atoms.len() as u8,
                tt: u64::from(*tt) * 0x0101_0101_0101_0101,
            };
            w.atoms[..atoms.len()].copy_from_slice(atoms);
            Some(w)
        }
        _ => None,
    }
}

/// The wide description of `root`, computing (iteratively) and caching those below it that
/// [`known_wide`] does not give.
fn wide_of(r: &mut Runner<'_, '_>, cx: &Context, root: u32) -> Result<Wide, Stop> {
    if let Some(w) = known_wide(r, cx, root) {
        return Ok(w);
    }
    let mut stack: Vec<(u32, bool)> = vec![(root, false)];
    while let Some((i, expanded)) = stack.pop() {
        if r.bitwise.wide.contains_key(&i) {
            continue;
        }
        let node = cx.node(i);
        if !expanded {
            stack.push((i, true));
            for c in node.children() {
                if known_wide(r, cx, c).is_none() {
                    stack.push((c, false));
                }
            }
            continue;
        }
        r.meter.charge(Counter::PassWork, 1)?;
        let known = |c: u32| known_wide(r, cx, c).expect("operands come first");
        let a = known(node.a);
        let b = if node.op == OpCode::Not {
            a
        } else {
            known(node.b)
        };
        r.bitwise.wide.insert(i, wide_op(cx, i, a, b));
    }
    Ok(r.bitwise.wide[&root])
}

/// Builds the minimum form of `tt` over `atoms` (in the order the table's variables use).
pub(super) fn emit(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    tt: u8,
    atoms: &[u32],
) -> Result<u32, Stop> {
    let (tmpl, _) = &min_forms().forms[tt as usize];
    let w = cx.width_of(atoms.first().copied().unwrap_or(0));
    let mut built: Vec<u32> = Vec::with_capacity(tmpl.len());
    for t in tmpl {
        r.meter.charge(Counter::PassWork, 1)?;
        let id = match *t {
            T::Var(k) => atoms[k as usize],
            T::Zero => r.build(cx, |cx| cx.mk_const(&crate::BitVec::zero(w)))?,
            T::Ones => r.build(cx, |cx| cx.mk_const(&crate::BitVec::ones(w)))?,
            T::Not(a) => {
                let a = built[a as usize];
                r.build(cx, |cx| cx.c_un(UnOp::Not, a))?
            }
            T::Bin(op, a, b) => {
                let (a, b) = (built[a as usize], built[b as usize]);
                r.build(cx, |cx| cx.c_bin(op, a, b))?
            }
        };
        built.push(id);
    }
    r.meter.check()?;
    Ok(*built.last().unwrap_or(&atoms[0]))
}

/// The most distinct constants (other than 0 and all-ones) a masked description splits on.
const MAX_MASKS: usize = 3;

/// The most nodes a masked description walks.
const MAX_MASKED_REGION: usize = 32;

/// Bitwise functions of at most three atoms and some constants (see the module notes): the atoms
/// (sorted by index), and per class of bit positions with one table for each root, the class's
/// positions (classes with equal tables merged) and the tables.
pub(crate) struct Masked {
    atoms: Vec<u32>,
    consts: Vec<u32>,
    classes: Vec<(BitVec, Vec<u8>)>,
    /// The region's operators.
    ops: u32,
}

impl Masked {
    /// The atoms, and each class of bit positions with the first root's table there.
    pub(crate) fn atoms_classes(&self) -> (&[u32], impl Iterator<Item = (&BitVec, u8)>) {
        (&self.atoms, self.classes.iter().map(|(m, t)| (m, t[0])))
    }
}

/// The masked description of `roots` (of one width), if their bitwise region below has at most
/// three atoms and [`MAX_MASKS`] constants.
pub(in crate::engine) fn masked(
    r: &mut Runner<'_, '_>,
    cx: &Context,
    roots: &[u32],
) -> Result<Option<Masked>, Stop> {
    /// A region node: an atom (its index), a constant (its index), or an operator over slots.
    #[derive(Clone, Copy)]
    enum Slot {
        Atom(usize),
        Const(usize),
        Op(OpCode, usize, usize),
    }
    // The region in post-order (a node's slot after its operands'), at most
    // `MAX_MASKED_REGION` nodes: small enough to search.
    // Fixed buffers: a region visits at most `MAX_MASKED_REGION` nodes, each pushing itself
    // and at most two operands.
    let mut ids = [0u32; MAX_MASKED_REGION];
    let mut slots = [Slot::Atom(0); MAX_MASKED_REGION];
    let mut len = 0usize;
    let (mut atoms, mut consts) = (Vec::with_capacity(3), Vec::with_capacity(2));
    let slot_of = |ids: &[u32], i: u32| ids.iter().position(|&j| j == i);
    let mut stack = [(0u32, false); 3 * MAX_MASKED_REGION + 2];
    let mut top = 0usize;
    for &n in roots.iter().rev() {
        stack[top] = (n, false);
        top += 1;
    }
    let mut visits = 0usize;
    let beyond = loop {
        if top == 0 {
            break false;
        }
        top -= 1;
        let (i, expanded) = stack[top];
        if slot_of(&ids[..len], i).is_some() {
            continue;
        }
        let node = cx.node(i);
        if expanded {
            let a = slot_of(&ids[..len], node.a).unwrap_or(0);
            let b = if node.op == OpCode::Not {
                a
            } else {
                slot_of(&ids[..len], node.b).unwrap_or(0)
            };
            ids[len] = i;
            slots[len] = Slot::Op(node.op, a, b);
            len += 1;
            continue;
        }
        visits += 1;
        if visits > MAX_MASKED_REGION || r.bitwise.beyond.contains_key(&i) {
            break true;
        }
        if !bitwise_op(node.op) {
            let slot = if cx.const_val(i).is_some() {
                consts.push(i);
                Slot::Const(consts.len() - 1)
            } else {
                atoms.push(i);
                Slot::Atom(atoms.len() - 1)
            };
            if atoms.len() > 3 || consts.len() > MAX_MASKS + 2 {
                break true;
            }
            ids[len] = i;
            slots[len] = slot;
            len += 1;
            continue;
        }
        stack[top] = (i, true);
        top += 1;
        for c in node.children() {
            if slot_of(&ids[..len], c).is_none() {
                stack[top] = (c, false);
                top += 1;
            }
        }
    };
    let (ids, slots) = (&ids[..len], &slots[..len]);
    if beyond {
        // So are the regions above a lone root (they contain its region).
        if let [n] = roots {
            r.bitwise.beyond.insert(*n, ());
        }
        r.meter.charge(Counter::PassWork, visits as u64)?;
        return Ok(None);
    }
    r.meter.charge(Counter::PassWork, visits as u64)?;
    // Atoms in index order: the tables' variables.
    let mut by_index: Vec<usize> = (0..atoms.len()).collect();
    by_index.sort_unstable_by_key(|&k| atoms[k]);
    let mut var = [0u8; 3];
    for (v, &k) in by_index.iter().enumerate() {
        var[k] = VARS[v];
    }
    atoms.sort_unstable();
    let w = cx.width_of(roots[0]);
    let values: Vec<BitVec> = consts
        .iter()
        .map(|&c| cx.const_val(c).unwrap_or(BitVec::zero(w)))
        .collect();
    // The constants that split: neither 0 nor all-ones.
    let mut splits: Vec<BitVec> = Vec::new();
    for v in &values {
        if !v.is_zero() && !v.is_ones() && !splits.contains(v) {
            splits.push(*v);
        }
    }
    if splits.len() > MAX_MASKS {
        if let [n] = roots {
            r.bitwise.beyond.insert(*n, ());
        }
        return Ok(None);
    }
    let mut classes: Vec<(BitVec, Vec<u8>)> = Vec::new();
    let mut vals: Vec<u8> = vec![0; slots.len()];
    for pattern in 0..1usize << splits.len() {
        // The class's positions: each splitting constant set (or clear) as the pattern says.
        let mut mask = BitVec::ones(w);
        for (k, v) in splits.iter().enumerate() {
            let v = if pattern >> k & 1 == 1 {
                *v
            } else {
                BitVec::un_unchecked(UnOp::Not, v)
            };
            mask = BitVec::bin_unchecked(BinOp::And, &mask, &v);
        }
        if mask.is_zero() {
            continue;
        }
        r.meter
            .charge(Counter::PassWork, slots.len() as u64 / 4 + 1)?;
        // Every slot's table in this class (a constant is all-ones on a class exactly when its
        // bits there are set: the class lies within it or outside it).
        for (k, slot) in slots.iter().enumerate() {
            vals[k] = match *slot {
                Slot::Atom(a) => var[a],
                Slot::Const(c) => {
                    if BitVec::bin_unchecked(BinOp::And, &values[c], &mask) == mask {
                        0xFF
                    } else {
                        0x00
                    }
                }
                Slot::Op(OpCode::Not, a, _) => !vals[a],
                Slot::Op(OpCode::And, a, b) => vals[a] & vals[b],
                Slot::Op(OpCode::Or, a, b) => vals[a] | vals[b],
                Slot::Op(_, a, b) => vals[a] ^ vals[b],
            };
        }
        let tables: Vec<u8> = roots
            .iter()
            .map(|&n| vals[slot_of(ids, n).unwrap_or(0)])
            .collect();
        match classes.iter_mut().find(|(_, t)| *t == tables) {
            Some((m, _)) => *m = BitVec::bin_unchecked(BinOp::Or, m, &mask),
            None => classes.push((mask, tables)),
        }
    }
    let ops = slots.iter().filter(|s| matches!(s, Slot::Op(..))).count() as u32;
    Ok(Some(Masked {
        atoms,
        consts,
        classes,
        ops,
    }))
}

/// Whether `a == b` (of one width) always (`Some(true)`) or never (`Some(false)`) holds, by
/// their masked descriptions: equal tables in every class, or complementary ones in a class.
pub(super) fn equal(
    r: &mut Runner<'_, '_>,
    cx: &Context,
    a: u32,
    b: u32,
) -> Result<Option<bool>, Stop> {
    if !bitwise_op(cx.node(a).op) && !bitwise_op(cx.node(b).op) {
        return Ok(None);
    }
    let Some(m) = masked(r, cx, &[a, b])? else {
        return Ok(None);
    };
    if m.classes.iter().all(|(_, t)| t[0] == t[1]) {
        return Ok(Some(true));
    }
    if m.classes.iter().any(|(_, t)| t[0] == !t[1]) {
        return Ok(Some(false));
    }
    Ok(None)
}

/// The operators and constants a template adds.
fn cost(tt: u8) -> u32 {
    min_forms().forms[tt as usize]
        .0
        .iter()
        .filter(|t| !matches!(t, T::Var(_)))
        .count() as u32
}

/// How a function of two classes is written (see the module notes): `t` on the mask's bits,
/// `u` elsewhere.
#[derive(Clone, Copy)]
enum Split {
    /// `f_t & mask`.
    And(u8),
    /// `f_t | mask` (the mask's bits all-ones).
    Or(u8),
    /// `f_u ^ mask`.
    Xor(u8),
    /// `f_u ^ (f_g & mask)`.
    Blend(u8, u8),
}

/// The bitwise pass at `n` for a function with constants: its masked description written
/// as the module notes say, when that is smaller.
fn masked_step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
    let Some(m) = masked(r, cx, &[n])? else {
        return Ok(Step::Normal(Fin::FINAL));
    };
    if m.consts.is_empty() || m.classes.len() > 2 {
        return Ok(Step::Normal(Fin::FINAL));
    }
    // A rewrite frees at most the region's operators: a form needing as many is not smaller.
    let cheapest = |t: u8| cost(t) + 1;
    let floor = match &m.classes[..] {
        [(_, t)] => cost(t[0]),
        [(_, t), (_, u)] => cheapest(t[0]).min(cheapest(u[0])),
        _ => u32::MAX,
    };
    if floor >= m.ops {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let mut canon = m.atoms.clone();
    canon.sort_by(|a, b| cx.order(*a, *b));
    let tt = |t: u8| remap(t, &m.atoms, &canon);
    let w = cx.width_of(n);
    // Each candidate: the function, its mask, and the nodes it adds (a mask that is not one of
    // the constants already there is one more).
    let is_old = |v: &BitVec| {
        m.consts
            .iter()
            .any(|&c| cx.const_val(c).as_ref() == Some(v))
    };
    let mut best: Option<(u32, Option<(Split, BitVec)>)> = None;
    let mut offer = |c: u32, s: Option<(Split, BitVec)>| {
        if best.as_ref().is_none_or(|(b, _)| c < *b) {
            best = Some((c, s));
        }
    };
    if let [(_, t)] = &m.classes[..] {
        offer(cost(tt(t[0])), None);
    } else {
        for (x, y) in [(0, 1), (1, 0)] {
            let (mask, t) = (m.classes[x].0, tt(m.classes[x].1[0]));
            let u = tt(m.classes[y].1[0]);
            let extra = 1 + u32::from(!is_old(&mask));
            if u == 0x00 {
                offer(cost(t) + extra, Some((Split::And(t), mask)));
            }
            if t == 0xFF {
                offer(cost(u) + extra, Some((Split::Or(u), mask)));
            }
            if t == !u {
                offer(cost(u) + extra, Some((Split::Xor(u), mask)));
            }
            offer(
                cost(u) + cost(t ^ u) + extra + 1,
                Some((Split::Blend(u, t ^ u), mask)),
            );
        }
    }
    let Some((estimate, split)) = best else {
        return Ok(Step::Normal(Fin::FINAL));
    };
    if estimate >= m.ops {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let mut bounds = m.atoms.clone();
    bounds.extend(&m.consts);
    if let Some(f) = worth_building(r, cx, n, &bounds, estimate)? {
        r.stats.passes.entry("bitwise").or_default().rejected_cost += 1;
        return Ok(Step::Normal(Fin::FINAL.and(f)));
    }
    let before = cx.len() as u32;
    let form = |r: &mut Runner<'_, '_>, cx: &mut Context, t: u8| -> Result<u32, Stop> {
        if canon.is_empty() || t == 0x00 || t == 0xFF {
            let v = if t == 0xFF {
                BitVec::ones(w)
            } else {
                BitVec::zero(w)
            };
            r.build(cx, |cx| cx.mk_const(&v))
        } else {
            emit(r, cx, t, &canon)
        }
    };
    let e = match split {
        None => form(r, cx, tt(m.classes[0].1[0]))?,
        Some((split, mask)) => {
            let k = r.build(cx, |cx| cx.mk_const(&mask))?;
            match split {
                Split::And(t) => {
                    let f = form(r, cx, t)?;
                    r.build(cx, |cx| cx.c_bin(BinOp::And, f, k))?
                }
                Split::Or(u) => {
                    let f = form(r, cx, u)?;
                    r.build(cx, |cx| cx.c_bin(BinOp::Or, f, k))?
                }
                Split::Xor(u) => {
                    let f = form(r, cx, u)?;
                    r.build(cx, |cx| cx.c_bin(BinOp::Xor, f, k))?
                }
                Split::Blend(u, g) => {
                    let (f, g) = (form(r, cx, u)?, form(r, cx, g)?);
                    let gm = r.build(cx, |cx| cx.c_bin(BinOp::And, g, k))?;
                    r.build(cx, |cx| cx.c_bin(BinOp::Xor, f, gm))?
                }
            }
        }
    };
    finish(r, cx, PassKind::Bitwise, n, e, before, &bounds, Fin::FINAL)
}

/// The most nodes a one-atom region walks.
const ONE_ATOM_REGION: usize = 64;

/// The bitwise pass at `n` for a function of one atom and any constants: `(x & a) ^ b`, when
/// that is smaller. Each bit of such a function is 0, 1, the atom's bit or its complement,
/// whatever the constants are, so its value at 0 (`b`) and where that differs from its value
/// at all-ones (`a`) say what it is; the classes of [`masked`] (at most [`MAX_MASKS`]
/// constants, two tables) are not needed.
fn one_atom_step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
    let w = cx.width_of(n);
    // The region, operands first; its one atom and its constants.
    let mut order: Vec<u32> = Vec::new();
    let mut seen: crate::hash::IdMap<u32, ()> = crate::hash::IdMap::default();
    let mut stack: Vec<(u32, bool)> = vec![(n, false)];
    let (mut atom, mut consts, mut ops) = (None, Vec::new(), 0u32);
    while let Some((i, expanded)) = stack.pop() {
        if expanded {
            order.push(i);
            continue;
        }
        if seen.insert(i, ()).is_some() {
            continue;
        }
        if seen.len() > ONE_ATOM_REGION {
            r.meter.charge(Counter::PassWork, seen.len() as u64)?;
            return Ok(Step::Normal(Fin::FINAL));
        }
        let node = cx.node(i);
        if bitwise_op(node.op) {
            ops += 1;
            stack.push((i, true));
            stack.extend(node.children().map(|c| (c, false)));
        } else if cx.const_val(i).is_some() {
            consts.push(i);
        } else if atom.is_some_and(|a| a != i) {
            r.meter.charge(Counter::PassWork, seen.len() as u64)?;
            return Ok(Step::Normal(Fin::FINAL));
        } else {
            atom = Some(i);
        }
    }
    r.meter.charge(Counter::PassWork, 2 * seen.len() as u64)?;
    let Some(x) = atom else {
        return Ok(Step::Normal(Fin::FINAL));
    };
    // The function at `x = v`.
    let at = |v: BitVec| -> BitVec {
        let mut vals: crate::hash::IdMap<u32, BitVec> = crate::hash::IdMap::default();
        vals.insert(x, v);
        for &c in &consts {
            vals.insert(c, cx.const_val(c).unwrap_or(BitVec::zero(w)));
        }
        for &i in &order {
            let node = cx.node(i);
            let v = match node.op {
                OpCode::Not => BitVec::un_unchecked(UnOp::Not, &vals[&node.a]),
                OpCode::And => BitVec::bin_unchecked(BinOp::And, &vals[&node.a], &vals[&node.b]),
                OpCode::Or => BitVec::bin_unchecked(BinOp::Or, &vals[&node.a], &vals[&node.b]),
                _ => BitVec::bin_unchecked(BinOp::Xor, &vals[&node.a], &vals[&node.b]),
            };
            vals.insert(i, v);
        }
        vals[&n]
    };
    let b = at(BitVec::zero(w));
    let a = BitVec::bin_unchecked(BinOp::Xor, &b, &at(BitVec::ones(w)));
    // The nodes the form adds: a constant alone, else `& a` unless every bit follows the
    // atom, and `^ b` (`~` for all ones) unless no bit is flipped or set.
    let is_old = |v: &BitVec| consts.iter().any(|&c| cx.const_val(c).as_ref() == Some(v));
    let estimate = if a.is_zero() {
        1
    } else {
        let masked = if a.is_ones() {
            0
        } else {
            1 + u32::from(!is_old(&a))
        };
        let flipped = match (b.is_zero(), b.is_ones()) {
            (true, _) => 0,
            (_, true) => 1,
            _ => 1 + u32::from(!is_old(&b)),
        };
        masked + flipped
    };
    if estimate >= ops {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let mut bounds = vec![x];
    bounds.extend(&consts);
    if let Some(f) = worth_building(r, cx, n, &bounds, estimate)? {
        r.stats.passes.entry("bitwise").or_default().rejected_cost += 1;
        return Ok(Step::Normal(Fin::FINAL.and(f)));
    }
    let before = cx.len() as u32;
    let e = r.build(cx, |cx| {
        let ka = cx.mk_const(&a)?;
        let kb = cx.mk_const(&b)?;
        let masked = cx.c_bin(BinOp::And, x, ka)?;
        cx.c_bin(BinOp::Xor, masked, kb)
    })?;
    finish(r, cx, PassKind::Bitwise, n, e, before, &bounds, Fin::FINAL)
}

/// Writes the function `tt` of `atoms` (at most three, sorted by index) at `n` as its minimum
/// form, when that is smaller; `fin` is what the node's candidates declined so far contribute.
fn write(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    n: u32,
    atoms: &[u32],
    tt: u8,
    fin: Fin,
) -> Result<Step, Stop> {
    // Canonical variable order: the context's order of the atoms, independent of indices.
    let mut canon = atoms.to_vec();
    canon.sort_by(|a, b| cx.order(*a, *b));
    let tt_c = remap(tt, atoms, &canon);
    // Upper bound on new nodes: the template's operators and constants.
    if let Some(f) = worth_building(r, cx, n, atoms, cost(tt_c))? {
        r.stats.passes.entry("bitwise").or_default().rejected_cost += 1;
        return Ok(Step::Normal(fin.and(f)));
    }
    let before = cx.len() as u32;
    // A constant needs a width: when the function ignores every atom, use the node's.
    let e = if canon.is_empty() {
        let w = cx.width_of(n);
        let v = if tt == 0 {
            BitVec::zero(w)
        } else {
            BitVec::ones(w)
        };
        r.build(cx, |cx| cx.mk_const(&v))?
    } else {
        emit(r, cx, tt_c, &canon)?
    };
    r.explain_with(|| crate::engine::Explanation::Bitwise {
        atoms: atoms.iter().map(|&a| cx.handle(a)).collect(),
        table: u64::from(tt),
    });
    finish(r, cx, PassKind::Bitwise, n, e, before, atoms, fin)
}

/// The most nodes of a bitwise tree [`hoist_cast`] reads.
const HOIST_NODES: usize = 64;

/// The low bits of values as a sum of multiples of the low bits of atoms, modulo a power of
/// two (see [`low_form`]).
#[derive(Default)]
struct Low {
    konst: u64,
    terms: Vec<(u32, u64)>,
}

/// The most nodes [`low_form`] reads for one sum.
const LOW_NODES: usize = 64;

/// Adds `k` times the low `bits` bits of node `i` to `out`, modulo `2^bits` (at most 63):
/// through sums, products and left shifts by constants, and through truncations, extensions
/// and masks that keep those bits; anything else is an atom. `false` past [`LOW_NODES`].
fn low_form(cx: &Context, i: u32, k: u64, bits: u16, out: &mut Low) -> bool {
    let m = (1u64 << bits) - 1;
    let mut todo = vec![(i, k & m)];
    let mut seen = 0usize;
    while let Some((i, k)) = todo.pop() {
        seen += 1;
        if seen > LOW_NODES {
            return false;
        }
        if k == 0 {
            continue;
        }
        let n = cx.node(i);
        let low = |c: u32| {
            cx.const_val(c)
                .map(|v| v.limbs().first().copied().unwrap_or(0) & m)
        };
        let keeps = |x: u32| cx.wid(x) >= bits;
        match n.op {
            OpCode::Const => {
                out.konst = out.konst.wrapping_add(k.wrapping_mul(low(i).unwrap_or(0))) & m
            }
            OpCode::Add => todo.extend([(n.a, k), (n.b, k)]),
            OpCode::Sub => todo.extend([(n.a, k), (n.b, k.wrapping_neg() & m)]),
            OpCode::Neg => todo.push((n.a, k.wrapping_neg() & m)),
            OpCode::Mul if low(n.b).is_some() => {
                todo.push((n.a, k.wrapping_mul(low(n.b).unwrap_or(0)) & m))
            }
            OpCode::Mul if low(n.a).is_some() => {
                todo.push((n.b, k.wrapping_mul(low(n.a).unwrap_or(0)) & m))
            }
            OpCode::Shl
                if cx
                    .const_val(n.b)
                    .and_then(|v| v.to_u64())
                    .is_some_and(|s| s < 64) =>
            {
                let s = cx.const_val(n.b).and_then(|v| v.to_u64()).unwrap_or(0);
                todo.push((n.a, (k << s) & m));
            }
            OpCode::Extract if n.b == 0 => todo.push((n.a, k)),
            OpCode::Zext | OpCode::Sext if keeps(n.a) => todo.push((n.a, k)),
            OpCode::And if low(n.b) == Some(m) => todo.push((n.a, k)),
            OpCode::And if low(n.a) == Some(m) => todo.push((n.b, k)),
            _ => match out.terms.iter_mut().find(|t| t.0 == i) {
                Some(t) => t.1 = t.1.wrapping_add(k) & m,
                None => out.terms.push((i, k)),
            },
        }
    }
    true
}

/// `x << a | x >>u b` (or joined by `^`: the halves share no bit) with counts below the width
/// whose sum is the width or nothing: `rotl(x, a)`. The counts are compared at the width's
/// logarithm as sums of multiples of what they are made of ([`low_form`]), so two spellings
/// of one count meet (`trunc<6>(u·83)` and `trunc<6>(u·109)`, extended, at 64 bits: `u·192`
/// has no low six bits). Constant counts are a rule's.
fn rotation(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
    let node = cx.node(n);
    let w = node.width;
    if !matches!(node.op, OpCode::Or | OpCode::Xor) || !w.is_power_of_two() || w < 2 {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let (l, s) = match (cx.node(node.a).op, cx.node(node.b).op) {
        (OpCode::Shl, OpCode::LShr) => (cx.node(node.a), cx.node(node.b)),
        (OpCode::LShr, OpCode::Shl) => (cx.node(node.b), cx.node(node.a)),
        _ => return Ok(Step::Normal(Fin::FINAL)),
    };
    let (x, a, b) = (l.a, l.b, s.b);
    if s.a != x || cx.const_val(a).is_some() || cx.const_val(b).is_some() {
        return Ok(Step::Normal(Fin::FINAL));
    }
    r.meter.charge(Counter::PassWork, 1)?;
    // Both counts below the width.
    let bits = w.trailing_zeros() as u16;
    let mut fin = Fin::FINAL;
    for count in [a, b] {
        let (f, g) = super::facts(r, cx, count)?;
        fin = fin.and(g);
        let below = f.is_some_and(|f| (bits..w).all(|i| f.known.known_zero().bit(i) == Some(true)));
        if !below {
            return Ok(Step::Normal(fin));
        }
    }
    // And their sum nothing at the low bits.
    let mut sum = Low::default();
    if !(low_form(cx, a, 1, bits, &mut sum) && low_form(cx, b, 1, bits, &mut sum))
        || sum.konst != 0
        || sum.terms.iter().any(|&(_, k)| k != 0)
    {
        return Ok(Step::Normal(fin));
    }
    let before = cx.len() as u32;
    let e = r.build(cx, |cx| cx.c_bin(BinOp::RotL, x, a))?;
    finish(r, cx, PassKind::Bitwise, n, e, before, &[x, a], fin)
}

/// A bitwise tree (`& | ^ ~`) whose leaves are extensions of one kind from one width `W`, and
/// constants, is the extension of the tree over the operands: `zext(a) & ~zext(b)` is
/// `zext(a & ~b)`, `~zext(a) & lowmask(W)` is `zext(~a)`, `sext(a) | sext(b)` is `sext(a | b)`.
/// Bitwise operators act by position, and a sign extension replicates one position, so a sign
/// extension of the narrow tree is the tree of the sign extensions when every constant's bits
/// from `W − 1` on agree (the tree's bit there is then the narrow result's sign). Above `W`
/// every zero extension is 0, so the wide tree is a constant bit there: 0 gives `zext(f)`, all
/// ones `~zext(~f)`. Committed when smaller: with two or more extensions, or one and a
/// constant it absorbs.
fn hoist_cast(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
    let u = cx.width_of(n);
    // The tree, operands first; its leaves.
    let mut order: Vec<u32> = Vec::new();
    let mut seen: Vec<u32> = Vec::new();
    let mut stack: Vec<(u32, bool)> = vec![(n, false)];
    let mut kind: Option<(OpCode, crate::Width)> = None;
    let mut casts = 0usize;
    let mut consts = 0usize;
    let mut narrow: Vec<u32> = Vec::new();
    while let Some((i, expanded)) = stack.pop() {
        if expanded {
            order.push(i);
            continue;
        }
        if seen.contains(&i) {
            continue;
        }
        seen.push(i);
        if seen.len() > HOIST_NODES {
            return Ok(Step::Normal(Fin::FINAL));
        }
        let node = cx.node(i);
        if cx.const_val(i).is_some() {
            consts += 1;
            continue;
        }
        match node.op {
            OpCode::Zext | OpCode::Sext => {
                let wa = cx.width_of(node.a);
                match kind {
                    Some(k) if k != (node.op, wa) => return Ok(Step::Normal(Fin::FINAL)),
                    _ => kind = Some((node.op, wa)),
                }
                casts += 1;
                narrow.push(node.a);
            }
            op if bitwise_op(op) => {
                stack.push((i, true));
                for c in node.children() {
                    stack.push((c, false));
                }
            }
            _ => return Ok(Step::Normal(Fin::FINAL)),
        }
    }
    let Some((k, w)) = kind else {
        return Ok(Step::Normal(Fin::FINAL));
    };
    if casts < 2 && consts == 0 {
        return Ok(Step::Normal(Fin::FINAL));
    }
    r.meter.charge(Counter::PassWork, order.len() as u64)?;
    // Every constant must agree with the extension: a sign extension of its low `W` bits, or
    // (for a zero extension) any bits, which decide the wide tree's value above `W`.
    let wide = |cx: &Context, i: u32| -> Option<BitVec> {
        let node = cx.node(i);
        if let Some(c) = cx.const_val(i) {
            return Some(c);
        }
        match node.op {
            OpCode::Zext | OpCode::Sext => Some(BitVec::zero(u)),
            _ => None,
        }
    };
    if k == OpCode::Sext {
        for &i in &seen {
            if let Some(c) = cx.const_val(i)
                && c.trunc(w).ok().and_then(|t| t.sext(u).ok()) != Some(c)
            {
                return Ok(Step::Normal(Fin::FINAL));
            }
        }
    }
    let before = cx.len() as u32;
    // The tree at `W` over the operands, and (for a zero extension) at the full width over
    // zeros for its value above `W`.
    let mut low: crate::hash::IdMap<u32, u32> = crate::hash::IdMap::default();
    let mut above: crate::hash::IdMap<u32, BitVec> = crate::hash::IdMap::default();
    for &i in &seen {
        let node = cx.node(i);
        if let Some(c) = cx.const_val(i) {
            let t = c.trunc(w).map_err(|e| Stop::Error(e.into()))?;
            low.insert(i, r.build(cx, |cx| cx.mk_const(&t))?);
            above.insert(i, c);
        } else if matches!(node.op, OpCode::Zext | OpCode::Sext) {
            low.insert(i, node.a);
            above.insert(i, BitVec::zero(u));
        }
    }
    for &i in &order {
        let node = cx.node(i);
        let (a, b) = (low[&node.a], node.b);
        let (va, vb) = (
            above[&node.a],
            wide(cx, node.b).or_else(|| above.get(&node.b).copied()),
        );
        let (l, v) = match node.op {
            OpCode::Not => (
                r.build(cx, |cx| cx.c_un(UnOp::Not, a))?,
                BitVec::un_unchecked(UnOp::Not, &va),
            ),
            op => {
                let bin = op.as_bin().unwrap_or(BinOp::And);
                let Some(vb) = vb else {
                    return Ok(Step::Normal(Fin::FINAL));
                };
                let lb = low[&b];
                (
                    r.build(cx, |cx| cx.c_bin(bin, a, lb))?,
                    BitVec::bin_unchecked(bin, &va, &vb),
                )
            }
        };
        low.insert(i, l);
        above.insert(i, v);
    }
    let f = low[&n];
    let e = if k == OpCode::Sext {
        r.build(cx, |cx| cx.c_sext(f, u.bits()))?
    } else {
        // The wide tree's bits above `W`.
        let v = above[&n];
        let hi = crate::facts::known::bv_lshr(&v, u32::from(w.bits()));
        let span = crate::facts::known::low_mask(u, u32::from(u.bits() - w.bits()));
        if hi.is_zero() {
            r.build(cx, |cx| cx.c_zext(f, u.bits()))?
        } else if hi == span {
            r.build(cx, |cx| {
                let nf = cx.c_un(UnOp::Not, f)?;
                let z = cx.c_zext(nf, u.bits())?;
                cx.c_un(UnOp::Not, z)
            })?
        } else {
            super::discard(r, cx, before);
            return Ok(Step::Normal(Fin::FINAL));
        }
    };
    narrow.sort_unstable();
    narrow.dedup();
    finish(r, cx, PassKind::Bitwise, n, e, before, &narrow, Fin::FINAL)
}

/// The bitwise pass at `n`. What a candidate it declines contributes stays in the result (see
/// the linear pass's `step`).
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &mut Context, n: u32) -> Result<Step, Stop> {
    if !bitwise_op(cx.node(n).op) {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let hoisted = match hoist_cast(r, cx, n)? {
        Step::Normal(f) => f,
        done => return Ok(done),
    };
    let hoisted = match rotation(r, cx, n)? {
        Step::Normal(f) => hoisted.and(f),
        done => return Ok(done),
    };
    let Some((atoms, tt)) = info_of(r, cx, n)? else {
        return Ok(Step::Normal(hoisted));
    };
    // More than three atoms (constants included): `n` is an atom itself, read first by classes
    // of bit positions, where the constants are not atoms.
    let first = if atoms == [n] {
        match masked_step(r, cx, n)? {
            Step::Normal(f) => match one_atom_step(r, cx, n)? {
                Step::Normal(g) => Step::Normal(f.and(g)),
                done => done,
            },
            done => done,
        }
    } else {
        write(r, cx, n, &atoms, tt, Fin::FINAL)?
    };
    let mut fin = match first {
        Step::Normal(f) => f.and(hoisted),
        done => return Ok(done),
    };
    // An atom that is a bitwise region of its own may hide that `n` reads three atoms or fewer
    // below it (see the module notes); read over more than six, `n` is an atom again.
    if atoms.iter().any(|&a| bitwise_op(cx.node(a).op)) {
        let wide = wide_of(r, cx, n)?;
        if wide.atoms().len() <= 3 && wide.atoms() != atoms && wide.atoms() != [n] {
            match write(r, cx, n, wide.atoms(), wide.tt as u8, fin)? {
                Step::Normal(f) => fin = f,
                done => return Ok(done),
            }
        }
    }
    // A chain of `&` or `|` no table reads whole, its operands in order (see `sort_chain`).
    if !matches!(cx.node(n).op, OpCode::And | OpCode::Or) {
        return Ok(Step::Normal(fin));
    }
    Ok(match super::sort_chain(r, cx, PassKind::Bitwise, n)? {
        Step::Normal(f) => Step::Normal(fin.and(f)),
        done => done,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `tt` over `from` as a table over `to`, entry by entry.
    fn reference(tt: u64, from: &[u32], to: &[u32]) -> u64 {
        (0..64).fold(0, |out, i| {
            let j = from.iter().enumerate().fold(0, |j, (k, a)| {
                let p = to.iter().position(|b| b == a).unwrap();
                j | ((i >> p) & 1) << k
            });
            out | ((tt >> j) & 1) << i
        })
    }

    /// A random table over `m` variables (its entries repeating past them).
    fn table(state: &mut u64, m: usize) -> u64 {
        *state ^= *state << 13;
        *state ^= *state >> 7;
        *state ^= *state << 17;
        (0..64).fold(0, |out, i| out | ((*state >> (i % (1 << m))) & 1) << i)
    }

    /// The atoms of subset `s` of `ids`.
    fn subset(ids: &[u32], s: usize) -> Vec<u32> {
        (0..ids.len())
            .filter(|k| s >> k & 1 == 1)
            .map(|k| ids[k])
            .collect()
    }

    #[test]
    fn wide_tables_move_between_atom_sets() {
        let ids = [3, 5, 8, 9, 12, 20];
        let mut state = 0x7769_6465;
        for big in 0..64usize {
            let to = subset(&ids, big);
            // Every subset of `to`, with tables over it.
            for small in (0..64usize).filter(|s| s & !big == 0) {
                let from = subset(&ids, small);
                for _ in 0..4 {
                    let tt = table(&mut state, from.len());
                    assert_eq!(
                        remap_wide(tt, &from, &to),
                        reference(tt, &from, &to),
                        "{from:?} -> {to:?}, {tt:#x}"
                    );
                }
            }
            // A table over all six that reads exactly `to`: pruning finds `to`, and its table.
            let mut tt = table(&mut state, to.len());
            while (0..to.len()).any(|k| {
                let (v, s) = (WIDE_VARS[k], 1u32 << k);
                (tt & v) >> s | (tt & !v) << s == tt
            }) {
                tt = table(&mut state, to.len());
            }
            let p = prune_wide(&ids, reference(tt, &to, &ids));
            assert_eq!(p.atoms(), &to[..]);
            assert_eq!(p.tt, tt, "{to:?}");
        }
    }
}

/// The pass's state for a call.
#[derive(Default)]
pub(crate) struct State {
    /// The bitwise pass's truth tables, per node.
    pub(crate) info: crate::hash::IdMap<u32, Info>,
    /// The bitwise pass's tables over up to six atoms, per node (read where three hide some).
    pub(crate) wide: crate::hash::IdMap<u32, Wide>,
    /// Nodes whose bitwise region is beyond the bitwise pass's reading with constants (see
    /// `pass::bitwise`): so is every region above them.
    pub(crate) beyond: crate::hash::IdMap<u32, ()>,
}