rigless 0.1.0

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Loads and stores, DDI 0403E.b A5.2.4, A5.3.5 to A5.3.10, and the other 16-bit ones of A5.2.
//!
//! Every instruction makes all its accesses before it writes a register. A fault leaves the block
//! as if the instruction never ran, and that only holds for registers it hasn't written yet.
//!
//! Where the manual says UNPREDICTABLE you get what the pseudocode does when it can run: a base
//! register in its own list, a writeback to the register loaded, a list of one register or none, a
//! store of the PC, a PC load inside an IT block. The pseudocode can't write R15 through `R[]`,
//! which B1.4.7 asserts it never does, so an UNPREDICTABLE encoding that would is UNDEFINED. The
//! glossary lets any UNPREDICTABLE instruction be UNDEFINED.

use std::mem::offset_of;

use cranelift_codegen::ir::{InstBuilder, Value, condcodes::IntCC, types};

use super::super::state::State;
use super::alu::{self, ShiftType};
use super::{Attributes, Emitter, Fault, Flag, Size, Translated, Undefined, bits};

/// How a load or store forms its address from its base register, A7.5.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Indexing {
    /// `index`: the access goes to the offset address rather than the base.
    index: bool,
    /// `add`: the offset is added to the base rather than taken from it.
    add: bool,
    /// `wback`: the offset address goes back to the base register.
    wback: bool,
}

/// Offset addressing, which leaves the base register alone.
const OFFSET: Indexing = Indexing {
    index: true,
    add: true,
    wback: false,
};

/// What a single load or store adds to its base register.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Offset {
    Immediate(u32),
    /// `Shift(R[m], SRType_LSL, shift, APSR.C)`, A7.7.44.
    Register {
        m: u32,
        shift: u32,
    },
}

/// Which way an LDM or STM walks from its base register.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
    /// From the base up, and the writeback past the last word, A7.7.40.
    IncrementAfter,
    /// From below the base, and the writeback to the first word, A7.7.41.
    DecrementBefore,
}

/// A load or store exclusive's register, base, offset and size.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Exclusive {
    t: u32,
    n: u32,
    imm32: u32,
    size: Size,
}

/// One load or store of a single register, decoded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Single {
    t: u32,
    n: u32,
    offset: Offset,
    indexing: Indexing,
    size: Size,
    /// A load sign-extends what it reads.
    signed: bool,
    /// LDRT and its kind, checked as an unprivileged access.
    unprivileged: bool,
}

impl Single {
    /// The offset form with an immediate, which most encodings are.
    fn immediate(t: u32, n: u32, imm32: u32, size: Size) -> Self {
        Self {
            t,
            n,
            offset: Offset::Immediate(imm32),
            indexing: OFFSET,
            size,
            signed: false,
            unprivileged: false,
        }
    }

    fn attributes(self) -> Attributes {
        Attributes {
            aligned: false,
            unprivileged: self.unprivileged,
        }
    }
}

/// LDR (literal), A7.7.43 encoding T1.
pub(super) fn load_literal16(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let address = literal(e, true, bits(hw, 7, 0) << 2);
    load_literal(e, bits(hw, 10, 8), address, Size::Word, false);
}

/// A5.2.4, load and store single data item, Table A5-5.
pub(super) fn load_store_single16(e: &mut Emitter<'_, '_>, hw: u16) -> Translated {
    let hw = u32::from(hw);
    let (t, n, imm5) = (bits(hw, 2, 0), bits(hw, 5, 3), bits(hw, 10, 6));
    let load = bits(hw, 11, 11) == 1;
    let (single, load) = match bits(hw, 15, 12) {
        0b0101 => {
            let (size, signed, load) = match bits(hw, 11, 9) {
                0b000 => (Size::Word, false, false),
                0b001 => (Size::Halfword, false, false),
                0b010 => (Size::Byte, false, false),
                0b011 => (Size::Byte, true, true),
                0b100 => (Size::Word, false, true),
                0b101 => (Size::Halfword, false, true),
                0b110 => (Size::Byte, false, true),
                _ => (Size::Halfword, true, true),
            };
            let single = Single {
                offset: Offset::Register {
                    m: bits(hw, 8, 6),
                    shift: 0,
                },
                signed,
                ..Single::immediate(t, n, 0, size)
            };
            (single, load)
        }
        0b0110 => (Single::immediate(t, n, imm5 << 2, Size::Word), load),
        0b0111 => (Single::immediate(t, n, imm5, Size::Byte), load),
        0b1000 => (Single::immediate(t, n, imm5 << 1, Size::Halfword), load),
        0b1001 => (
            Single::immediate(bits(hw, 10, 8), 13, bits(hw, 7, 0) << 2, Size::Word),
            load,
        ),
        _ => return Err(Undefined),
    };
    if load {
        load_one(e, single);
    } else {
        store_one(e, single);
    }
    Ok(())
}

/// STM, A7.7.156 encoding T1, which always writes back.
pub(super) fn store_multiple16(e: &mut Emitter<'_, '_>, hw: u16) -> Translated {
    let hw = u32::from(hw);
    store_multiple(
        e,
        bits(hw, 10, 8),
        bits(hw, 7, 0),
        true,
        Step::IncrementAfter,
    )
}

/// LDM, A7.7.40 encoding T1, which writes back unless the base is in the list.
pub(super) fn load_multiple16(e: &mut Emitter<'_, '_>, hw: u16) -> Translated {
    let hw = u32::from(hw);
    let (n, registers) = (bits(hw, 10, 8), bits(hw, 7, 0));
    load_multiple(
        e,
        n,
        registers,
        registers & (1 << n) == 0,
        Step::IncrementAfter,
    )
}

/// PUSH, A7.7.99 encoding T1, where M is LR.
pub(super) fn push16(e: &mut Emitter<'_, '_>, hw: u16) -> Translated {
    let hw = u32::from(hw);
    store_multiple(
        e,
        13,
        bits(hw, 8, 8) << 14 | bits(hw, 7, 0),
        true,
        Step::DecrementBefore,
    )
}

/// POP, A7.7.98 encoding T1, where P is the PC.
pub(super) fn pop16(e: &mut Emitter<'_, '_>, hw: u16) -> Translated {
    let hw = u32::from(hw);
    load_multiple(
        e,
        13,
        bits(hw, 8, 8) << 15 | bits(hw, 7, 0),
        true,
        Step::IncrementAfter,
    )
}

/// A5.3.5, load multiple and store multiple, Table A5-16. POP and PUSH are LDM and STMDB on SP
/// with writeback, which their pseudocode does the same way.
pub(super) fn load_store_multiple(e: &mut Emitter<'_, '_>, hw1: u16, hw2: u16) -> Translated {
    let (hw1, list) = (u32::from(hw1), u32::from(hw2));
    let n = bits(hw1, 3, 0);
    let wback = bits(hw1, 5, 5) == 1;
    // Bits 15 and 13 can't name the PC or SP here, since A7.7.156 builds the list as
    // `'0':M:'0':register_list` and A7.7.40 as `P:M:'0':register_list`.
    let (stores, loads) = (list & 0x5FFF, list & 0xDFFF);
    match (bits(hw1, 8, 7), bits(hw1, 4, 4)) {
        (0b01, 0) => store_multiple(e, n, stores, wback, Step::IncrementAfter),
        (0b01, 1) => load_multiple(e, n, loads, wback, Step::IncrementAfter),
        (0b10, 0) => store_multiple(e, n, stores, wback, Step::DecrementBefore),
        (0b10, 1) => load_multiple(e, n, loads, wback, Step::DecrementBefore),
        _ => Err(Undefined),
    }
}

/// A5.3.6, load and store dual or exclusive, and table branch, Table A5-17.
pub(super) fn load_store_dual_exclusive_table_branch(
    e: &mut Emitter<'_, '_>,
    hw1: u16,
    hw2: u16,
) -> Translated {
    let (hw1, hw2) = (u32::from(hw1), u32::from(hw2));
    let (n, t) = (bits(hw1, 3, 0), bits(hw2, 15, 12));
    let imm8 = bits(hw2, 7, 0);
    let exclusive = |imm32, size| Exclusive { t, n, imm32, size };
    match (bits(hw1, 8, 7), bits(hw1, 5, 4)) {
        (0b00, 0b00) => store_exclusive(e, bits(hw2, 11, 8), exclusive(imm8 << 2, Size::Word)),
        (0b00, 0b01) => load_exclusive(e, exclusive(imm8 << 2, Size::Word)),
        (0b01, 0b00) => match bits(hw2, 7, 4) {
            0b0100 => store_exclusive(e, bits(hw2, 3, 0), exclusive(0, Size::Byte)),
            0b0101 => store_exclusive(e, bits(hw2, 3, 0), exclusive(0, Size::Halfword)),
            _ => Err(Undefined),
        },
        (0b01, 0b01) => match bits(hw2, 7, 4) {
            0b0000 => {
                table_branch(e, n, bits(hw2, 3, 0), Size::Byte);
                Ok(())
            }
            0b0001 => {
                table_branch(e, n, bits(hw2, 3, 0), Size::Halfword);
                Ok(())
            }
            0b0100 => load_exclusive(e, exclusive(0, Size::Byte)),
            0b0101 => load_exclusive(e, exclusive(0, Size::Halfword)),
            _ => Err(Undefined),
        },
        _ => dual(e, hw1, hw2),
    }
}

/// A5.3.7, load word, Table A5-18.
pub(super) fn load_word(e: &mut Emitter<'_, '_>, hw1: u16, hw2: u16) -> Translated {
    load32(e, u32::from(hw1), u32::from(hw2), Size::Word)
}

/// A5.3.8, load halfword and memory hints, Table A5-19.
pub(super) fn load_halfword_hints(e: &mut Emitter<'_, '_>, hw1: u16, hw2: u16) -> Translated {
    load32(e, u32::from(hw1), u32::from(hw2), Size::Halfword)
}

/// A5.3.9, load byte and memory hints, Table A5-20.
pub(super) fn load_byte_hints(e: &mut Emitter<'_, '_>, hw1: u16, hw2: u16) -> Translated {
    load32(e, u32::from(hw1), u32::from(hw2), Size::Byte)
}

/// A5.3.10, store single data item, Table A5-21.
pub(super) fn store_single(e: &mut Emitter<'_, '_>, hw1: u16, hw2: u16) -> Translated {
    let (hw1, hw2) = (u32::from(hw1), u32::from(hw2));
    let size = match bits(hw1, 6, 5) {
        0b00 => Size::Byte,
        0b01 => Size::Halfword,
        0b10 => Size::Word,
        _ => return Err(Undefined),
    };
    // Every store's encodings make a base of PC UNDEFINED, A7.7.158 to A7.7.170.
    if bits(hw1, 3, 0) == 15 {
        return Err(Undefined);
    }
    store_one(e, form32(hw1, hw2, size, false)?);
    Ok(())
}

/// `ClearExclusiveLocal()`, B2.3.7, which is all CLREX does, A7.7.23.
pub(super) fn clear_exclusive(e: &mut Emitter<'_, '_>) {
    let open = e.constant(0);
    e.store_field(offset_of!(State, exclusive_valid), open);
}

/// The loads of Tables A5-18 to A5-20, and the memory hints that share their encodings.
fn load32(e: &mut Emitter<'_, '_>, hw1: u32, hw2: u32, size: Size) -> Translated {
    let (signed, n, t) = (bits(hw1, 8, 8) == 1, bits(hw1, 3, 0), bits(hw2, 15, 12));
    if signed && size == Size::Word {
        return Err(Undefined);
    }
    // A narrow load to the PC is PLD, PLI or an unallocated hint, A7.6.1, and a hint changes
    // nothing a processor without caches holds.
    let hint = t == 15 && size != Size::Word;
    if n == 15 {
        if hint {
            return Ok(());
        }
        let address = literal(e, bits(hw1, 7, 7) == 1, bits(hw2, 11, 0));
        load_literal(e, t, address, size, signed);
        return Ok(());
    }
    let single = form32(hw1, hw2, size, signed)?;
    if t == 15 {
        // Tables A5-19 and A5-20 make a narrow PC load with writeback or unprivileged
        // UNPREDICTABLE, and LDRT can't write the PC at all, A7.7.66.
        if single.unprivileged || (hint && single.indexing.wback) {
            return Err(Undefined);
        }
        if hint {
            return Ok(());
        }
    }
    load_one(e, single);
    Ok(())
}

/// The addressing of A5.3.7 to A5.3.10's single loads and stores, by bit 7 of the first halfword
/// and `op2`, bits 11 to 6 of the second.
fn form32(hw1: u32, hw2: u32, size: Size, signed: bool) -> Result<Single, Undefined> {
    let mut single = Single {
        signed,
        ..Single::immediate(bits(hw2, 15, 12), bits(hw1, 3, 0), bits(hw2, 11, 0), size)
    };
    if bits(hw1, 7, 7) == 1 {
        return Ok(single);
    }
    let op2 = bits(hw2, 11, 6);
    if op2 == 0 {
        single.offset = Offset::Register {
            m: bits(hw2, 3, 0),
            shift: bits(hw2, 5, 4),
        };
        return Ok(single);
    }
    if op2 >> 5 == 0 {
        return Err(Undefined);
    }
    single.offset = Offset::Immediate(bits(hw2, 7, 0));
    let (p, u, w) = (
        bits(hw2, 10, 10) == 1,
        bits(hw2, 9, 9) == 1,
        bits(hw2, 8, 8) == 1,
    );
    match (p, u, w) {
        (true, true, false) => single.unprivileged = true,
        (false, _, false) => return Err(Undefined),
        _ => {
            single.indexing = Indexing {
                index: p,
                add: u,
                wback: w,
            };
        }
    }
    Ok(single)
}

/// `R[n] = value`, B1.4.7, which keeps SP word-aligned.
fn set(e: &mut Emitter<'_, '_>, n: u32, value: Value) {
    let value = if n == 13 {
        e.b.ins().band_imm_s(value, !3)
    } else {
        value
    };
    e.set_reg(n, value);
}

/// The address a single load or store accesses, and the offset address its writeback writes,
/// A7.5.
fn addresses(e: &mut Emitter<'_, '_>, single: Single) -> (Value, Value) {
    let base = e.reg(single.n);
    let offset = match single.offset {
        Offset::Immediate(imm32) => e.constant(imm32),
        Offset::Register { m, shift } => {
            let rm = e.reg(m);
            let carry = e.flag(Flag::C);
            alu::shift_c(e, rm, ShiftType::Lsl, shift, carry).0
        }
    };
    let offset_addr = if single.indexing.add {
        e.b.ins().iadd(base, offset)
    } else {
        e.b.ins().isub(base, offset)
    };
    let address = if single.indexing.index {
        offset_addr
    } else {
        base
    };
    (address, offset_addr)
}

/// LDR, LDRH, LDRSH, LDRB, LDRSB and their unprivileged forms, A7.7.42 to A7.7.66.
fn load_one(e: &mut Emitter<'_, '_>, single: Single) {
    let (address, offset_addr) = addresses(e, single);
    let data = e.load(address, single.size, single.attributes());
    let data = extend(e, data, single.size, single.signed);
    // Rt wins over the writeback when `wback && n == t` everywhere but the byte loads, since
    // A7.7.42 writes Rt last and A7.7.45 writes it first.
    let rt_first = single.size == Size::Byte;
    if rt_first {
        set(e, single.t, data);
    }
    if single.indexing.wback {
        set(e, single.n, offset_addr);
    }
    if rt_first {
        return;
    }
    if single.t == 15 {
        // `LoadWritePC()`. An address that isn't word-aligned is UNPREDICTABLE, A7.7.42, and
        // branches all the same.
        e.branch_exchange(data);
    } else {
        set(e, single.t, data);
    }
}

/// STR, STRH, STRB and their unprivileged forms, A7.7.158 to A7.7.170. Rt of PC stores this
/// instruction's address plus 4, UNPREDICTABLE as that is.
fn store_one(e: &mut Emitter<'_, '_>, single: Single) {
    let (address, offset_addr) = addresses(e, single);
    let value = e.reg(single.t);
    e.store(address, value, single.size, single.attributes());
    if single.indexing.wback {
        set(e, single.n, offset_addr);
    }
}

/// `Align(PC,4) + imm32`, or minus when not `add`, the address of a literal, A7.7.43, which is
/// known when the instruction is translated.
fn literal(e: &Emitter<'_, '_>, add: bool, imm32: u32) -> u32 {
    let base = e.pc().wrapping_add(4) & !3;
    if add {
        base.wrapping_add(imm32)
    } else {
        base.wrapping_sub(imm32)
    }
}

/// LDR, LDRH, LDRSH, LDRB and LDRSB (literal), A7.7.43 to A7.7.63.
fn load_literal(e: &mut Emitter<'_, '_>, t: u32, address: u32, size: Size, signed: bool) {
    let address = e.constant(address);
    let data = e.load(address, size, Attributes::default());
    let data = extend(e, data, size, signed);
    if t == 15 {
        e.branch_exchange(data);
    } else {
        set(e, t, data);
    }
}

/// `data` as the load gives it, zero-extended, or sign-extended from `size` when `signed`.
fn extend(e: &mut Emitter<'_, '_>, data: Value, size: Size, signed: bool) -> Value {
    let narrow = match (signed, size) {
        (true, Size::Byte) => types::I8,
        (true, Size::Halfword) => types::I16,
        _ => return data,
    };
    let narrow = e.b.ins().ireduce(narrow, data);
    e.b.ins().sextend(types::I32, narrow)
}

/// The first address an LDM or STM of `bytes` from `base` accesses, and what its writeback writes.
fn span(e: &mut Emitter<'_, '_>, base: Value, bytes: u32, step: Step) -> (Value, Value) {
    let bytes = i64::from(bytes);
    match step {
        Step::IncrementAfter => (base, e.b.ins().iadd_imm_s(base, bytes)),
        Step::DecrementBefore => {
            let below = e.b.ins().iadd_imm_s(base, -bytes);
            (below, below)
        }
    }
}

/// LDM, LDMDB and POP, A7.7.40, A7.7.41 and A7.7.98: a word into each register of `registers`,
/// the lowest numbered from the lowest address.
fn load_multiple(
    e: &mut Emitter<'_, '_>,
    n: u32,
    registers: u32,
    wback: bool,
    step: Step,
) -> Translated {
    if wback && n == 15 {
        return Err(Undefined);
    }
    let base = e.reg(n);
    let (mut address, written) = span(e, base, 4 * registers.count_ones(), step);
    let mut loaded = Vec::new();
    for i in (0..16).filter(|i| registers & (1 << i) != 0) {
        loaded.push((i, e.load(address, Size::Word, Attributes::ALIGNED)));
        address = e.b.ins().iadd_imm_s(address, 4);
    }
    for &(i, value) in loaded.iter().filter(|&&(i, _)| i < 15) {
        set(e, i, value);
    }
    // A base in its own list keeps what it loaded, A7.7.40, UNPREDICTABLE as that is with `!`.
    if wback && registers & (1 << n) == 0 {
        set(e, n, written);
    }
    if let Some(&(15, target)) = loaded.last() {
        e.branch_exchange(target);
    }
    Ok(())
}

/// STM, STMDB and PUSH, A7.7.156, A7.7.157 and A7.7.99: each register of `registers` to a word,
/// the lowest numbered to the lowest address. A base in its own list stores what it held before,
/// which the UNKNOWN of A7.7.156 allows.
fn store_multiple(
    e: &mut Emitter<'_, '_>,
    n: u32,
    registers: u32,
    wback: bool,
    step: Step,
) -> Translated {
    if wback && n == 15 {
        return Err(Undefined);
    }
    let base = e.reg(n);
    let (mut address, written) = span(e, base, 4 * registers.count_ones(), step);
    for i in (0..15).filter(|i| registers & (1 << i) != 0) {
        let value = e.reg(i);
        e.store(address, value, Size::Word, Attributes::ALIGNED);
        address = e.b.ins().iadd_imm_s(address, 4);
    }
    if wback {
        set(e, n, written);
    }
    Ok(())
}

/// LDRD and STRD, A7.7.49, A7.7.50 and A7.7.163.
fn dual(e: &mut Emitter<'_, '_>, hw1: u32, hw2: u32) -> Translated {
    let (n, t, t2) = (bits(hw1, 3, 0), bits(hw2, 15, 12), bits(hw2, 11, 8));
    let imm32 = bits(hw2, 7, 0) << 2;
    let load = bits(hw1, 4, 4) == 1;
    let indexing = Indexing {
        index: bits(hw1, 8, 8) == 1,
        add: bits(hw1, 7, 7) == 1,
        wback: bits(hw1, 5, 5) == 1,
    };
    if (load && (t == 15 || t2 == 15)) || (!load && indexing.wback && n == 15) {
        return Err(Undefined);
    }
    let (address, offset_addr) = if load && n == 15 {
        // LDRD (literal) has no writeback, so W is UNPREDICTABLE and ignored, A7.7.50. It reads
        // from the word-aligned PC, which A5.1.2 names for it, and which an aligned PC is anyway.
        let address = literal(e, indexing.add, imm32);
        (e.constant(address), None)
    } else {
        let single = Single {
            indexing,
            ..Single::immediate(t, n, imm32, Size::Word)
        };
        let (address, offset_addr) = addresses(e, single);
        (address, indexing.wback.then_some(offset_addr))
    };
    let second = e.b.ins().iadd_imm_s(address, 4);
    if load {
        let first_word = e.load(address, Size::Word, Attributes::ALIGNED);
        let second_word = e.load(second, Size::Word, Attributes::ALIGNED);
        set(e, t, first_word);
        set(e, t2, second_word);
    } else {
        let (first_word, second_word) = (e.reg(t), e.reg(t2));
        e.store(address, first_word, Size::Word, Attributes::ALIGNED);
        e.store(second, second_word, Size::Word, Attributes::ALIGNED);
    }
    if let Some(offset_addr) = offset_addr {
        set(e, n, offset_addr);
    }
    Ok(())
}

/// LDREX, LDREXB and LDREXH, A7.7.51 to A7.7.53, which open the local monitor's Exclusive Access
/// state, A3.4.1.
fn load_exclusive(e: &mut Emitter<'_, '_>, exclusive: Exclusive) -> Translated {
    let Exclusive { t, n, imm32, size } = exclusive;
    if t == 15 {
        return Err(Undefined);
    }
    let base = e.reg(n);
    let address = e.b.ins().iadd_imm_s(base, i64::from(imm32));
    let data = e.load(address, size, Attributes::ALIGNED);
    // A Cortex-M4's monitor holds no address and takes any store exclusive as matching, 100166
    // section 3.6, so the state holds only whether it's in the Exclusive Access state.
    let exclusive = e.constant(1);
    e.store_field(offset_of!(State, exclusive_valid), exclusive);
    set(e, t, data);
    Ok(())
}

/// STREX, STREXB and STREXH, A7.7.164 to A7.7.166, with B2.3.7's `ExclusiveMonitorsPass()`.
///
/// Any other store leaves the monitor alone, one of Table A3-2's IMPLEMENTATION DEFINED choices
/// for a store to the tagged address.
fn store_exclusive(e: &mut Emitter<'_, '_>, d: u32, exclusive: Exclusive) -> Translated {
    let Exclusive { t, n, imm32, size } = exclusive;
    if d == 15 {
        return Err(Undefined);
    }
    let base = e.reg(n);
    let address = e.b.ins().iadd_imm_s(base, i64::from(imm32));
    let value = e.reg(t);
    if size != Size::Byte {
        // `ExclusiveMonitorsPass()` faults an unaligned address before it looks at the monitor,
        // so an open monitor doesn't excuse one.
        let misaligned = e.b.ins().band_imm_s(address, i64::from(size.bytes() - 1));
        let misaligned = e.b.ins().icmp_imm_s(IntCC::NotEqual, misaligned, 0);
        e.raise_if(misaligned, Fault::Unaligned);
    }
    let monitor = e.load_field(offset_of!(State, exclusive_valid));
    let pass = e.b.create_block();
    let join = e.b.create_block();
    e.b.append_block_param(join, types::I32);
    let failed = e.constant(1);
    e.b.ins().brif(monitor, pass, &[], join, &[failed.into()]);
    e.b.seal_block(pass);
    e.b.switch_to_block(pass);
    e.store(address, value, size, Attributes::ALIGNED);
    clear_exclusive(e);
    let stored = e.constant(0);
    e.b.ins().jump(join, &[stored.into()]);
    e.b.seal_block(join);
    e.b.switch_to_block(join);
    let status = e.b.block_params(join)[0];
    set(e, d, status);
    Ok(())
}

/// TBB and TBH, A7.7.182. TBH reads with `MemU[]`, so its table may be unaligned unless
/// `CCR.UNALIGN_TRP` is set, A3.2.1.
fn table_branch(e: &mut Emitter<'_, '_>, n: u32, m: u32, size: Size) {
    let base = e.reg(n);
    let index = e.reg(m);
    let index = if size == Size::Halfword {
        e.b.ins().ishl_imm_s(index, 1)
    } else {
        index
    };
    let address = e.b.ins().iadd(base, index);
    let halfwords = e.load(address, size, Attributes::default());
    let forward = e.b.ins().ishl_imm_s(halfwords, 1);
    let pc = e.reg(15);
    let target = e.b.ins().iadd(pc, forward);
    e.branch(target);
}

#[cfg(test)]
mod tests {
    //! Each encoding runs on a [`Bench`]. The syntax beside it is what it was assembled from, or
    //! for an UNPREDICTABLE form an assembler refuses, the form it was changed to by hand. The
    //! UNDEFINED encodings, and the attributes each access asks for, are read from what the
    //! translator emits, since a run can't show you either.

    use cranelift_codegen::ir::{self, InstructionData, Opcode, ValueDef};
    use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};

    use super::super::super::family::helpers;
    use super::super::testing::{Bench, CODE, DEVICE, RAM};
    use super::super::{decode16, decode32};
    use super::*;
    use crate::emulator::AccessKind;
    use crate::emulator::Exit;
    use crate::soc::Width;

    /// Where the tests keep their data, with room on both sides for offsets.
    const BASE: u32 = RAM + 0x2000;
    /// Where a test with a literal places its instruction, so there's code on both sides of it.
    const AT: u32 = CODE + 0x20;
    /// The bytes [`load`] reads, and what each size makes of them.
    const BYTES: [u8; 4] = [0x81, 0x92, 0xA3, 0xB4];
    const WORD: u32 = 0xB4A3_9281;
    const HALFWORD: u32 = 0x9281;
    const SIGNED_HALFWORD: u32 = 0xFFFF_9281;
    const BYTE: u32 = 0x81;
    const SIGNED_BYTE: u32 = 0xFFFF_FF81;
    /// What [`store`] stores, and the bytes of RAM it hasn't.
    const STORED: [u8; 4] = [0x44, 0x33, 0x22, 0x11];
    const UNTOUCHED: u8 = 0xA5;

    /// A bench about to run `code` with each of `registers` set, and RAM around [`BASE`] filled
    /// with [`UNTOUCHED`].
    fn ready(code: &[u16], registers: &[(usize, u32)]) -> Bench {
        let mut bench = Bench::new(code);
        bench.write(BASE - 0x1000, &[UNTOUCHED; 0x3000]);
        for &(n, value) in registers {
            bench.core.state.r[n] = value;
        }
        bench
    }

    /// A bench about to run `code` from [`AT`].
    fn ready_at(code: &[u16], registers: &[(usize, u32)]) -> Bench {
        let mut bench = ready(&[], registers);
        bench.place(AT, code);
        bench.core.state.r[15] = AT;
        bench
    }

    /// Runs `instructions`, each of which must retire.
    fn run(bench: &mut Bench, instructions: u32) {
        assert_eq!(bench.run(instructions).1, u64::from(instructions));
    }

    fn put(bench: &mut Bench, address: u32, words: &[u32]) {
        let bytes: Vec<u8> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
        bench.write(address, &bytes);
    }

    fn words<const N: usize>(bench: &Bench, address: u32) -> [u32; N] {
        std::array::from_fn(|k| bench.word(address + 4 * u32::try_from(k).unwrap()))
    }

    fn bytes<const N: usize>(bench: &Bench, address: u32) -> [u8; N] {
        std::array::from_fn(|k| {
            let at = address + u32::try_from(k).unwrap();
            bench.word(at & !3).to_le_bytes()[usize::try_from(at & 3).unwrap()]
        })
    }

    /// Runs the 16-bit load or store `hw` with `r1` holding `0x1122_3344`, `r2` and SP [`BASE`],
    /// `r3` 8 and `0x8081_8283` at `at`, and answers `r1` and the word at `at` after it.
    fn single16(hw: u16, at: u32) -> (u32, u32) {
        let mut bench = ready(&[hw], &[(1, 0x1122_3344), (2, BASE), (3, 8), (13, BASE)]);
        put(&mut bench, at, &[0x8081_8283]);
        run(&mut bench, 1);
        let state = &bench.core.state;
        assert_eq!((state.r[2], state.r[3], state.r[13]), (BASE, 8, BASE));
        (state.r[1], bench.word(at))
    }

    /// Runs the 32-bit load `code` from [`AT`] with `r2` holding [`BASE`], `r3` 2, and [`BYTES`]
    /// at `at`, and answers `r1` and `r2` after it.
    fn load(code: [u16; 2], at: u32) -> (u32, u32) {
        let mut bench = ready_at(&code, &[(2, BASE), (3, 2)]);
        bench.write(at, &BYTES);
        run(&mut bench, 1);
        (bench.core.state.r[1], bench.core.state.r[2])
    }

    /// Runs the 32-bit store `code` with `r1` holding `0x1122_3344`, `r2` [`BASE`] and `r3` 2,
    /// and answers the five bytes from `at` and `r2` after it.
    fn store(code: [u16; 2], at: u32) -> ([u8; 5], u32) {
        let mut bench = ready(&code, &[(1, 0x1122_3344), (2, BASE), (3, 2)]);
        run(&mut bench, 1);
        (bytes(&bench, at), bench.core.state.r[2])
    }

    /// The five bytes [`store`] leaves when it stores `size` bytes.
    fn stored(size: usize) -> [u8; 5] {
        std::array::from_fn(|k| if k < size { STORED[k] } else { UNTOUCHED })
    }

    /// A call a translation makes into the core.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum Call {
        /// A read or write of so many bytes, with its attributes.
        Read(u32, Attributes),
        Write(u32, Attributes),
        /// A fault raised, by its number.
        Raise(u32),
    }

    const PLAIN: Attributes = Attributes {
        aligned: false,
        unprivileged: false,
    };
    const UNPRIVILEGED: Attributes = Attributes {
        aligned: false,
        unprivileged: true,
    };
    const ALIGNED: Attributes = Attributes::ALIGNED;

    /// Translates `code` alone at [`CODE`], and answers the calls it makes into the core, or that
    /// it's UNDEFINED.
    fn translated(code: &[u16]) -> Result<Vec<Call>, Undefined> {
        let mut function = ir::Function::new();
        function
            .signature
            .params
            .push(ir::AbiParam::new(types::I64));
        function
            .signature
            .returns
            .push(ir::AbiParam::new(types::I32));
        let mut context = FunctionBuilderContext::new();
        let mut builder = FunctionBuilder::new(&mut function, &mut context);
        let entry = builder.create_block();
        builder.append_block_params_for_function_params(entry);
        builder.switch_to_block(entry);
        let mut e = Emitter::new(&mut builder, types::I64);
        e.begin(0, CODE, 2 * u32::try_from(code.len()).unwrap(), 0);
        match *code {
            [hw] => decode16(&mut e, hw),
            [hw1, hw2] => decode32(&mut e, hw1, hw2),
            _ => panic!("an instruction is one or two halfwords"),
        }?;
        Ok(calls(builder.func))
    }

    fn calls(function: &ir::Function) -> Vec<Call> {
        let dfg = &function.dfg;
        let constant = |value: Value| {
            let ValueDef::Result(inst, _) = dfg.value_def(dfg.resolve_aliases(value)) else {
                panic!("{value} isn't an instruction's");
            };
            let InstructionData::UnaryImm { imm, .. } = dfg.insts[inst] else {
                panic!("{value} isn't a constant");
            };
            imm.bits().cast_unsigned()
        };
        let word = |value| u32::try_from(constant(value) & u64::from(u32::MAX)).unwrap();
        let address = |helper: usize| u64::try_from(helper).unwrap();
        let read = address(helpers::read as *const () as usize);
        let write = address(helpers::write as *const () as usize);
        let raise = address(helpers::raise as *const () as usize);
        let mut calls = Vec::new();
        for block in function.layout.blocks() {
            for inst in function.layout.block_insts(block) {
                if dfg.insts[inst].opcode() != Opcode::CallIndirect {
                    continue;
                }
                let args = dfg.inst_args(inst);
                let callee = constant(args[0]);
                calls.push(if callee == read {
                    Call::Read(word(args[3]), Attributes::from_bits(word(args[4])))
                } else if callee == write {
                    Call::Write(word(args[4]), Attributes::from_bits(word(args[5])))
                } else if callee == raise {
                    Call::Raise(word(args[2]))
                } else {
                    panic!("a call to no helper the core has");
                });
            }
        }
        calls
    }

    /// A7.7.43: T1 reads from `Align(PC,4)`, so the instructions at 0 and 2 read the same word.
    #[test]
    fn ldr_literal_reads_from_the_word_aligned_pc() {
        // ldr r3, [pc, #8] then ldr r4, [pc, #8]
        let mut bench = ready(&[0x4B02, 0x4C02], &[]);
        put(&mut bench, CODE + 12, &[0xCAFE_F00D]);
        run(&mut bench, 2);
        assert_eq!(bench.core.state.r[3..5], [0xCAFE_F00D, 0xCAFE_F00D]);
    }

    /// Table A5-5's register forms access `R[n] + R[m]`, and the narrow loads extend as their
    /// names say.
    #[test]
    fn the_16_bit_register_forms_access_rn_plus_rm() {
        let (at, same) = (BASE + 8, 0x8081_8283);
        assert_eq!(single16(0x50D1, at), (0x1122_3344, 0x1122_3344), "str");
        assert_eq!(single16(0x52D1, at), (0x1122_3344, 0x8081_3344), "strh");
        assert_eq!(single16(0x54D1, at), (0x1122_3344, 0x8081_8244), "strb");
        assert_eq!(single16(0x56D1, at), (0xFFFF_FF83, same), "ldrsb");
        assert_eq!(single16(0x58D1, at), (same, same), "ldr");
        assert_eq!(single16(0x5AD1, at), (0x8283, same), "ldrh");
        assert_eq!(single16(0x5CD1, at), (0x83, same), "ldrb");
        assert_eq!(single16(0x5ED1, at), (0xFFFF_8283, same), "ldrsh");
    }

    /// Table A5-5's immediate forms scale `imm5` by the size, and the SP forms `imm8` by 4.
    #[test]
    fn the_16_bit_immediate_forms_scale_their_offset_by_the_size() {
        let (r1, same) = (0x1122_3344, 0x8081_8283);
        assert_eq!(single16(0x67D1, BASE + 124), (r1, r1), "str r1, [r2, #124]");
        assert_eq!(
            single16(0x6FD1, BASE + 124),
            (same, same),
            "ldr r1, [r2, #124]"
        );
        assert_eq!(
            single16(0x77D1, BASE + 28),
            (r1, 0x4481_8283),
            "strb r1, [r2, #31]"
        );
        assert_eq!(
            single16(0x7FD1, BASE + 28),
            (0x80, same),
            "ldrb r1, [r2, #31]"
        );
        assert_eq!(
            single16(0x87D1, BASE + 60),
            (r1, 0x3344_8283),
            "strh r1, [r2, #62]"
        );
        assert_eq!(
            single16(0x8FD1, BASE + 60),
            (0x8081, same),
            "ldrh r1, [r2, #62]"
        );
        assert_eq!(
            single16(0x91FF, BASE + 1020),
            (r1, r1),
            "str r1, [sp, #1020]"
        );
        assert_eq!(
            single16(0x99FF, BASE + 1020),
            (same, same),
            "ldr r1, [sp, #1020]"
        );
    }

    /// A7.7.156 and A7.7.40, encodings T1: STM always writes back, and LDM unless it loads the
    /// base.
    #[test]
    fn stm_and_ldm_16_walk_up_from_the_base() {
        // stm r0!, {r1, r2, r7} then ldm r0!, {r1, r2, r7}
        let mut bench = ready(&[0xC086, 0xC886], &[(0, BASE), (1, 1), (2, 2), (7, 7)]);
        run(&mut bench, 1);
        assert_eq!(words::<4>(&bench, BASE), [1, 2, 7, 0xA5A5_A5A5]);
        assert_eq!(bench.core.state.r[0], BASE + 12);
        bench.core.state.r[0] = BASE;
        bench.core.state.r[1..8].fill(0);
        run(&mut bench, 1);
        assert_eq!(bench.core.state.r[0..3], [BASE + 12, 1, 2]);
        assert_eq!(bench.core.state.r[7], 7);

        // ldm r0, {r0, r1}
        let mut bench = ready(&[0xC803], &[(0, BASE)]);
        put(&mut bench, BASE, &[0xA, 0xB]);
        run(&mut bench, 1);
        assert_eq!(
            bench.core.state.r[0..2],
            [0xA, 0xB],
            "the base keeps what it loaded"
        );
    }

    /// A7.7.156 T1 with the base in the list: the lowest stores what it held, and any other the
    /// UNKNOWN value A7.7.156 allows, which is what it held too.
    #[test]
    fn stm_16_with_its_base_in_the_list_stores_the_base_as_it_was() {
        // stm r1!, {r1, r2}
        let mut bench = ready(&[0xC106], &[(1, BASE), (2, 0x22)]);
        run(&mut bench, 1);
        assert_eq!(words::<2>(&bench, BASE), [BASE, 0x22]);
        assert_eq!(bench.core.state.r[1], BASE + 8);
        // stm r2!, {r1, r2}
        let mut bench = ready(&[0xC206], &[(1, 0x11), (2, BASE)]);
        run(&mut bench, 1);
        assert_eq!(words::<2>(&bench, BASE), [0x11, BASE]);
        assert_eq!(bench.core.state.r[2], BASE + 8);
    }

    /// A7.7.99 and A7.7.98, encodings T1: M is LR and P is the PC, which POP loads with
    /// `LoadWritePC()`.
    #[test]
    fn push_and_pop_16_move_the_stack_and_pop_branches() {
        // push {r1, r2, lr} then pop {r1, r2, pc}
        let mut bench = ready(&[0xB506, 0xBD06], &[(1, 1), (2, 2), (13, BASE), (14, 0xE)]);
        run(&mut bench, 1);
        assert_eq!(words::<3>(&bench, BASE - 12), [1, 2, 0xE]);
        assert_eq!(bench.core.state.r[13], BASE - 12);
        put(&mut bench, BASE - 12, &[0x11, 0x22, 0x101]);
        run(&mut bench, 1);
        let state = &bench.core.state;
        assert_eq!(state.r[1..3], [0x11, 0x22]);
        assert_eq!((state.r[13], state.r[15], state.t), (BASE, 0x100, 1));

        // push {r3} then pop {r4}
        let mut bench = ready(&[0xB408, 0xBC10], &[(3, 3), (13, BASE)]);
        run(&mut bench, 2);
        assert_eq!(bench.word(BASE - 4), 3);
        assert_eq!((bench.core.state.r[4], bench.core.state.r[13]), (3, BASE));
    }

    /// A2.3.1's `BXWritePC()`: a PC loaded with bit 0 clear clears `EPSR.T`.
    #[test]
    fn a_pc_popped_without_bit_0_clears_the_thumb_bit() {
        // pop {r1, r2, pc}
        let mut bench = ready(&[0xBD06], &[(13, BASE)]);
        put(&mut bench, BASE, &[0, 0, 0x200]);
        run(&mut bench, 1);
        assert_eq!((bench.core.state.r[15], bench.core.state.t), (0x200, 0));
    }

    /// Table A5-16's loads: LDM up from the base, LDMDB down from it, each with and without
    /// writeback, and POP as LDM on SP.
    #[test]
    fn the_32_bit_load_multiples_walk_from_the_base() {
        // (code, Rn, Rn before, Rn after, the third register loaded)
        let cases: [([u16; 2], usize, u32, u32, usize); 5] = [
            ([0xE8B0, 0x8006], 0, BASE, BASE + 12, 15), // ldm.w r0!, {r1, r2, pc}
            ([0xE890, 0x0006], 0, BASE, BASE, 3),       // ldm.w r0, {r1, r2}
            ([0xE930, 0x4006], 0, BASE + 12, BASE, 14), // ldmdb r0!, {r1, r2, lr}
            ([0xE910, 0x0006], 0, BASE + 8, BASE + 8, 3), // ldmdb r0, {r1, r2}
            ([0xE8BD, 0x8006], 13, BASE, BASE + 12, 15), // pop.w {r1, r2, pc}
        ];
        for (code, n, before, after, third) in cases {
            let mut bench = ready(&code, &[(n, before)]);
            put(&mut bench, BASE, &[0x11, 0x22, 0x301]);
            run(&mut bench, 1);
            let state = &bench.core.state;
            assert_eq!(state.r[n], after, "{code:04X?}");
            assert_eq!(state.r[1..3], [0x11, 0x22], "{code:04X?}");
            let third_loaded = match third {
                15 => 0x300,
                14 => 0x301,
                _ => 0,
            };
            assert_eq!(state.r[third], third_loaded, "{code:04X?}");
        }
    }

    /// Table A5-16's stores: STM up from the base, STMDB down from it, each with and without
    /// writeback, and PUSH as STMDB on SP.
    #[test]
    fn the_32_bit_store_multiples_walk_from_the_base() {
        // (code, Rn, Rn before, Rn after, where the first word goes)
        let cases: [([u16; 2], usize, u32, u32, u32); 5] = [
            ([0xE8A0, 0x4006], 0, BASE, BASE + 12, BASE), // stm.w r0!, {r1, r2, lr}
            ([0xE880, 0x4006], 0, BASE, BASE, BASE),      // stm.w r0, {r1, r2, lr}
            ([0xE920, 0x4006], 0, BASE + 12, BASE, BASE), // stmdb r0!, {r1, r2, lr}
            ([0xE900, 0x4006], 0, BASE + 12, BASE + 12, BASE), // stmdb r0, {r1, r2, lr}
            ([0xE92D, 0x4006], 13, BASE + 12, BASE, BASE), // push.w {r1, r2, lr}
        ];
        for (code, n, before, after, first) in cases {
            let mut bench = ready(&code, &[(1, 1), (2, 2), (14, 0xE), (n, before)]);
            run(&mut bench, 1);
            assert_eq!(bench.core.state.r[n], after, "{code:04X?}");
            assert_eq!(
                words::<4>(&bench, first),
                [1, 2, 0xE, 0xA5A5_A5A5],
                "{code:04X?}"
            );
        }
    }

    /// The register lists of A7.7.156 and A7.7.40 are `'0':M:'0':register_list` and
    /// `P:M:'0':register_list`, so bit 13 never names SP and a store's bit 15 never the PC.
    #[test]
    fn the_32_bit_lists_ignore_the_bits_that_cant_name_a_register() {
        // stm.w r0, {r1, r2} with bits 15 and 13 set
        let mut bench = ready(&[0xE880, 0xA006], &[(0, BASE), (1, 1), (2, 2)]);
        run(&mut bench, 1);
        assert_eq!(words::<3>(&bench, BASE), [1, 2, 0xA5A5_A5A5]);
        // ldm.w r0, {r1, r2} with bit 13 set
        let mut bench = ready(&[0xE890, 0x2006], &[(0, BASE), (13, BASE + 0x100)]);
        run(&mut bench, 1);
        assert_eq!(bench.core.state.r[13], BASE + 0x100);
    }

    /// POP and PUSH of one register are LDR and STR with writeback, A7.7.98 T3 and A7.7.99 T3.
    #[test]
    fn pop_and_push_of_one_register_are_ldr_and_str() {
        // push.w {r4} then pop.w {r5} then pop.w {pc}
        let mut bench = ready(&[0xF84D, 0x4D04, 0xF85D, 0x5B04, 0xF85D, 0xFB04], &[(4, 4)]);
        bench.core.state.r[13] = BASE;
        run(&mut bench, 2);
        assert_eq!(bench.word(BASE - 4), 4);
        assert_eq!((bench.core.state.r[5], bench.core.state.r[13]), (4, BASE));
        bench.core.state.r[13] = BASE - 4;
        put(&mut bench, BASE - 4, &[0x41]);
        run(&mut bench, 1);
        assert_eq!(
            (bench.core.state.r[15], bench.core.state.r[13]),
            (0x40, BASE)
        );
    }

    /// Table A5-18 and A7.7.42 to A7.7.44: every way LDR forms its address.
    #[test]
    fn ldr_32_forms_every_address_the_manual_does() {
        let cases = [
            ([0xF8D2, 0x1FFF], BASE + 4095, BASE),  // ldr.w r1, [r2, #4095]
            ([0xF852, 0x1CFF], BASE - 255, BASE),   // ldr r1, [r2, #-255]
            ([0xF852, 0x1F04], BASE + 4, BASE + 4), // ldr r1, [r2, #4]!
            ([0xF852, 0x1D04], BASE - 4, BASE - 4), // ldr r1, [r2, #-4]!
            ([0xF852, 0x1B04], BASE, BASE + 4),     // ldr r1, [r2], #4
            ([0xF852, 0x1904], BASE, BASE - 4),     // ldr r1, [r2], #-4
            ([0xF852, 0x1033], BASE + 16, BASE),    // ldr.w r1, [r2, r3, lsl #3]
            ([0xF8DF, 0x1008], AT + 4 + 8, BASE),   // ldr.w r1, [pc, #8]
            ([0xF85F, 0x1008], AT + 4 - 8, BASE),   // ldr.w r1, [pc, #-8]
            ([0xF852, 0x1EFF], BASE + 255, BASE),   // ldrt r1, [r2, #255]
        ];
        for (code, at, r2) in cases {
            assert_eq!(load(code, at), (WORD, r2), "{code:04X?}");
        }
    }

    /// Table A5-19 and A7.7.54 to A7.7.65: every way LDRH and LDRSH form their address.
    #[test]
    fn ldrh_and_ldrsh_form_every_address_the_manual_does() {
        let cases = [
            ([0xF8B2, 0x1FFF], BASE + 4095, BASE), // ldrh.w r1, [r2, #4095]
            ([0xF832, 0x1CFF], BASE - 255, BASE),  // ldrh r1, [r2, #-255]
            ([0xF832, 0x1F02], BASE + 2, BASE + 2), // ldrh r1, [r2, #2]!
            ([0xF832, 0x1902], BASE, BASE - 2),    // ldrh r1, [r2], #-2
            ([0xF832, 0x1013], BASE + 4, BASE),    // ldrh.w r1, [r2, r3, lsl #1]
            ([0xF8BF, 0x1008], AT + 4 + 8, BASE),  // ldrh.w r1, [pc, #8]
            ([0xF83F, 0x1008], AT + 4 - 8, BASE),  // ldrh.w r1, [pc, #-8]
            ([0xF832, 0x1EFF], BASE + 255, BASE),  // ldrht r1, [r2, #255]
        ];
        for (code, at, r2) in cases {
            assert_eq!(load(code, at), (HALFWORD, r2), "{code:04X?}");
            let signed = [code[0] | 0x100, code[1]];
            assert_eq!(load(signed, at), (SIGNED_HALFWORD, r2), "{signed:04X?}");
        }
    }

    /// Table A5-20 and A7.7.45 to A7.7.61: every way LDRB and LDRSB form their address.
    #[test]
    fn ldrb_and_ldrsb_form_every_address_the_manual_does() {
        let cases = [
            ([0xF892, 0x1FFF], BASE + 4095, BASE), // ldrb.w r1, [r2, #4095]
            ([0xF812, 0x1CFF], BASE - 255, BASE),  // ldrb r1, [r2, #-255]
            ([0xF812, 0x1F01], BASE + 1, BASE + 1), // ldrb r1, [r2, #1]!
            ([0xF812, 0x1901], BASE, BASE - 1),    // ldrb r1, [r2], #-1
            ([0xF812, 0x1023], BASE + 8, BASE),    // ldrb.w r1, [r2, r3, lsl #2]
            ([0xF89F, 0x1008], AT + 4 + 8, BASE),  // ldrb.w r1, [pc, #8]
            ([0xF81F, 0x1008], AT + 4 - 8, BASE),  // ldrb.w r1, [pc, #-8]
            ([0xF812, 0x1EFF], BASE + 255, BASE),  // ldrbt r1, [r2, #255]
        ];
        for (code, at, r2) in cases {
            assert_eq!(load(code, at), (BYTE, r2), "{code:04X?}");
            let signed = [code[0] | 0x100, code[1]];
            assert_eq!(load(signed, at), (SIGNED_BYTE, r2), "{signed:04X?}");
        }
    }

    /// A7.7.42: LDR to the PC is `LoadWritePC()`, after the writeback.
    #[test]
    fn ldr_to_the_pc_branches() {
        // ldr.w pc, [r2, #4] then ldr pc, [r2], #4
        for (code, r2) in [([0xF8D2, 0xF004], BASE), ([0xF852, 0xFB04], BASE + 4)] {
            let mut bench = ready(&code, &[(2, BASE)]);
            put(&mut bench, BASE, &[0x81, 0x81]);
            run(&mut bench, 1);
            let state = &bench.core.state;
            assert_eq!(
                (state.r[15], state.t, state.r[2]),
                (0x80, 1, r2),
                "{code:04X?}"
            );
        }
        // ldr.w pc, [pc, #8]
        let mut bench = ready_at(&[0xF8DF, 0xF008], &[]);
        put(&mut bench, AT + 12, &[0x81]);
        run(&mut bench, 1);
        assert_eq!((bench.core.state.r[15], bench.core.state.t), (0x80, 1));
    }

    /// A7.6.1: PLD, PLI and the unallocated hints of Tables A5-19 and A5-20 touch nothing.
    #[test]
    fn the_memory_hints_change_nothing() {
        let hints = [
            [0xF892, 0xFFFF], // pld [r2, #4095]
            [0xF812, 0xFCFF], // pld [r2, #-255]
            [0xF812, 0xF023], // pld [r2, r3, lsl #2]
            [0xF89F, 0xF008], // pld [pc, #8]
            [0xF81F, 0xF008], // pld [pc, #-8]
            [0xF992, 0xFFFF], // pli [r2, #4095]
            [0xF912, 0xFCFF], // pli [r2, #-255]
            [0xF912, 0xF023], // pli [r2, r3, lsl #2]
            [0xF99F, 0xF008], // pli [pc, #8]
            [0xF91F, 0xF008], // pli [pc, #-8]
            [0xF8B2, 0xFFFF], // ldrh.w pc, [r2, #4095]
            [0xF832, 0xFCFF], // ldrh pc, [r2, #-255]
            [0xF832, 0xF013], // ldrh.w pc, [r2, r3, lsl #1]
            [0xF8BF, 0xF008], // ldrh.w pc, [pc, #8]
            [0xF9B2, 0xFFFF], // ldrsh.w pc, [r2, #4095]
            [0xF932, 0xFCFF], // ldrsh pc, [r2, #-255]
            [0xF932, 0xF013], // ldrsh.w pc, [r2, r3, lsl #1]
            [0xF93F, 0xF008], // ldrsh.w pc, [pc, #-8]
        ];
        for code in hints {
            let mut bench = ready_at(&code, &[(2, DEVICE), (3, 2)]);
            let before = bench.core.state.clone();
            run(&mut bench, 1);
            assert!(bench.bus.accesses.is_empty(), "{code:04X?}");
            let after = &bench.core.state;
            assert_eq!(after.r[..15], before.r[..15], "{code:04X?}");
            assert_eq!(after.r[15], AT + 4, "{code:04X?}");
        }
    }

    /// Table A5-21 and A7.7.158 to A7.7.170: every way STR, STRH and STRB form their address,
    /// each storing its own size.
    #[test]
    fn the_32_bit_stores_form_every_address_the_manual_does() {
        let cases = [
            ([0xF8C2, 0x1FFF], BASE + 4095, BASE, 4), // str.w r1, [r2, #4095]
            ([0xF842, 0x1CFF], BASE - 255, BASE, 4),  // str r1, [r2, #-255]
            ([0xF842, 0x1F04], BASE + 4, BASE + 4, 4), // str r1, [r2, #4]!
            ([0xF842, 0x1904], BASE, BASE - 4, 4),    // str r1, [r2], #-4
            ([0xF842, 0x1033], BASE + 16, BASE, 4),   // str.w r1, [r2, r3, lsl #3]
            ([0xF842, 0x1EFF], BASE + 255, BASE, 4),  // strt r1, [r2, #255]
            ([0xF8A2, 0x1FFF], BASE + 4095, BASE, 2), // strh.w r1, [r2, #4095]
            ([0xF822, 0x1CFF], BASE - 255, BASE, 2),  // strh r1, [r2, #-255]
            ([0xF822, 0x1F02], BASE + 2, BASE + 2, 2), // strh r1, [r2, #2]!
            ([0xF822, 0x1902], BASE, BASE - 2, 2),    // strh r1, [r2], #-2
            ([0xF822, 0x1013], BASE + 4, BASE, 2),    // strh.w r1, [r2, r3, lsl #1]
            ([0xF822, 0x1EFF], BASE + 255, BASE, 2),  // strht r1, [r2, #255]
            ([0xF882, 0x1FFF], BASE + 4095, BASE, 1), // strb.w r1, [r2, #4095]
            ([0xF802, 0x1CFF], BASE - 255, BASE, 1),  // strb r1, [r2, #-255]
            ([0xF802, 0x1F01], BASE + 1, BASE + 1, 1), // strb r1, [r2, #1]!
            ([0xF802, 0x1901], BASE, BASE - 1, 1),    // strb r1, [r2], #-1
            ([0xF802, 0x1023], BASE + 8, BASE, 1),    // strb.w r1, [r2, r3, lsl #2]
            ([0xF802, 0x1EFF], BASE + 255, BASE, 1),  // strbt r1, [r2, #255]
        ];
        for (code, at, r2, size) in cases {
            assert_eq!(store(code, at), (stored(size), r2), "{code:04X?}");
        }
    }

    /// A7.7.49 and A7.7.163: LDRD and STRD in every addressing form, the words at the address
    /// and the next.
    #[test]
    fn ldrd_and_strd_move_two_words_in_every_form() {
        // (code, where the words are, r3 after)
        let base = BASE;
        let cases = [
            ([0xE9D3, 0x12FF], base + 1020, base), // ldrd r1, r2, [r3, #1020]
            ([0xE953, 0x1202], base - 8, base),    // ldrd r1, r2, [r3, #-8]
            ([0xE9F3, 0x1202], base + 8, base + 8), // ldrd r1, r2, [r3, #8]!
            ([0xE873, 0x1202], base, base - 8),    // ldrd r1, r2, [r3], #-8
        ];
        for (code, at, r3) in cases {
            let mut bench = ready(&code, &[(3, base)]);
            put(&mut bench, at, &[0x11, 0x22]);
            run(&mut bench, 1);
            assert_eq!(bench.core.state.r[1..4], [0x11, 0x22, r3], "{code:04X?}");
            let strd = [code[0] & !0x10, code[1]];
            let mut bench = ready(&strd, &[(1, 1), (2, 2), (3, base)]);
            run(&mut bench, 1);
            assert_eq!(words::<2>(&bench, at), [1, 2], "{code:04X?}");
            assert_eq!(bench.core.state.r[3], r3, "{code:04X?}");
        }
    }

    /// A7.7.50: LDRD (literal) reads from `Align(PC,4)` plus or minus its offset.
    #[test]
    fn ldrd_literal_reads_from_the_pc() {
        // ldrd r1, r2, [pc, #8] then ldrd r1, r2, [pc, #-16]
        for (code, at) in [([0xE9DF, 0x1202], AT + 12), ([0xE95F, 0x1204], AT - 12)] {
            let mut bench = ready_at(&code, &[]);
            put(&mut bench, at, &[0x11, 0x22]);
            run(&mut bench, 1);
            assert_eq!(bench.core.state.r[1..3], [0x11, 0x22], "{code:04X?}");
        }
    }

    /// A3.4.1 and B2.3.7: a store exclusive stores and answers 0 only after a load exclusive,
    /// and opens the monitor whether it stored or not.
    #[test]
    fn a_store_exclusive_stores_only_after_a_load_exclusive() {
        // (ldrex, strex, size in bytes)
        let pairs: [([u16; 2], [u16; 2], usize); 3] = [
            // ldrex r1, [r2, #1020] then strex r3, r1, [r2, #1020]
            ([0xE852, 0x1FFF], [0xE842, 0x13FF], 4),
            ([0xE8D2, 0x1F4F], [0xE8C2, 0x1F43], 1), // ldrexb r1, [r2] then strexb r3, r1, [r2]
            ([0xE8D2, 0x1F5F], [0xE8C2, 0x1F53], 2), // ldrexh r1, [r2] then strexh r3, r1, [r2]
        ];
        for (ldrex, strex, size) in pairs {
            let at = if size == 4 { BASE + 1020 } else { BASE };
            let mut bench = ready(&[ldrex[0], ldrex[1], strex[0], strex[1]], &[(2, BASE)]);
            bench.write(at, &STORED);
            run(&mut bench, 1);
            let mask = u32::MAX >> (32 - 8 * size);
            assert_eq!(bench.core.state.r[1], 0x1122_3344 & mask, "{ldrex:04X?}");
            assert_eq!(bench.core.state.exclusive_valid, 1);
            bench.core.state.r[1] = 0x5566_7788;
            run(&mut bench, 1);
            assert_eq!(bench.core.state.r[3], 0, "{strex:04X?} stores");
            assert_eq!(bench.word(at), 0x1122_3344 & !mask | 0x5566_7788 & mask);
            assert_eq!(bench.core.state.exclusive_valid, 0);
            bench.core.state.r[15] = 4;
            bench.core.state.r[1] = 0x99;
            run(&mut bench, 1);
            assert_eq!(bench.core.state.r[3], 1, "{strex:04X?} doesn't store");
            assert_eq!(bench.word(at), 0x1122_3344 & !mask | 0x5566_7788 & mask);
        }
    }

    /// The Cortex-M4's monitor holds no address, 100166 section 3.6, so a store exclusive to
    /// another address than the load's still stores.
    #[test]
    fn a_store_exclusive_anywhere_passes_after_a_load_exclusive() {
        // ldrex r1, [r2, #1020] then strex r3, r4, [r2]
        let mut bench = ready(&[0xE852, 0x1FFF, 0xE842, 0x4300], &[(2, BASE), (4, 0x1234)]);
        run(&mut bench, 2);
        assert_eq!((bench.core.state.r[3], bench.word(BASE)), (0, 0x1234));
    }

    /// A7.7.182: TBB and TBH branch forward by twice the entry, from the PC, with a table that
    /// may follow the instruction.
    #[test]
    fn tbb_and_tbh_branch_forward_by_twice_the_entry() {
        // tbb [r1, r2] then tbh [r1, r2, lsl #1]
        for (code, target) in [
            ([0xE8D1, 0xF002], 4 + 2 * 0x03),
            ([0xE8D1, 0xF012], 4 + 2 * 0x0403),
        ] {
            let mut bench = ready(&code, &[(1, BASE), (2, 2)]);
            bench.write(BASE, &[0, 0, 3, 0, 3, 4]);
            run(&mut bench, 1);
            assert_eq!(bench.core.state.r[15], target, "{code:04X?}");
        }
        // tbb [pc, r2] then tbh [pc, r2, lsl #1], with the table after the instruction
        for (code, target) in [
            ([0xE8DF, 0xF002], 4 + 2 * 0x07),
            ([0xE8DF, 0xF012], 4 + 2 * 0x0807),
        ] {
            let index = if code[1] & 0x10 == 0 { 2 } else { 1 };
            let mut bench = ready(&[code[0], code[1], 0x0605, 0x0807, 0x0A09], &[(2, index)]);
            run(&mut bench, 1);
            assert_eq!(bench.core.state.r[15], target, "{code:04X?}");
        }
    }

    /// A load that reaches the bus asks for its own width, and the core sign-extends what comes
    /// back.
    #[test]
    fn a_narrow_load_from_the_bus_extends_what_it_reads() {
        // ldrsh r1, [r2, r3]
        let mut bench = ready(&[0x5ED1], &[(2, DEVICE), (3, 2)]);
        bench.bus.answer = 0x8001;
        assert_eq!(bench.run(1), (Exit::Returned, 1));
        assert_eq!(bench.core.state.r[1], 0xFFFF_8001);
        let access = bench.bus.accesses[0];
        assert_eq!(
            (access.kind, access.address, access.width),
            (AccessKind::Read, u64::from(DEVICE) + 2, Width::W16)
        );
        // strb r1, [r2, r3], which writes the low byte alone, A7.7.160
        let mut bench = ready(&[0x54D1], &[(1, 0x1122_3344), (2, DEVICE), (3, 2)]);
        assert_eq!(bench.run(1), (Exit::Returned, 1));
        let access = bench.bus.accesses[0];
        assert_eq!(
            (access.kind, access.address, access.width, access.value),
            (AccessKind::Write, u64::from(DEVICE) + 2, Width::W8, 0x44)
        );
    }

    /// B2.3.5: `MemU_with_priv()` makes an unaligned access a byte at a time, and since A3.5.7
    /// leaves one to a device UNPREDICTABLE, that's what the device sees, even where a halfword
    /// would fit.
    #[test]
    fn an_unaligned_access_reaches_the_bus_a_byte_at_a_time() {
        let pieces = |code: u16, offset: u32| {
            let mut bench = ready(&[code], &[(1, 0x1122_3344), (2, DEVICE), (3, offset)]);
            assert_eq!(bench.run(1), (Exit::Returned, 1));
            bench
                .bus
                .accesses
                .iter()
                .map(|access| {
                    (
                        access.address - u64::from(DEVICE),
                        access.width,
                        access.value,
                    )
                })
                .collect::<Vec<_>>()
        };
        // ldr r1, [r2, r3]
        assert_eq!(
            pieces(0x58D1, 2),
            [2, 3, 4, 5].map(|byte| (byte, Width::W8, 0)),
        );
        // str r1, [r2, r3]
        assert_eq!(
            pieces(0x50D1, 3),
            [(3, 0x44), (4, 0x33), (5, 0x22), (6, 0x11)].map(|(byte, value)| (
                byte,
                Width::W8,
                value
            )),
        );
    }

    /// A fault leaves every register as it was, writebacks and the PC included, even after an
    /// access of the same instruction went through.
    #[test]
    fn a_failed_access_writes_no_register() {
        let cases: [(&[u16], usize); 6] = [
            (&[0xC886], 0),         // ldm r0!, {r1, r2, r7}
            (&[0xBD06], 13),        // pop {r1, r2, pc}
            (&[0xF850, 0x1F04], 0), // ldr r1, [r0, #4]!
            (&[0xE870, 0x1202], 0), // ldrd r1, r2, [r0], #-8
            (&[0xC006], 0),         // stm r0!, {r1, r2}
            (&[0xE8E0, 0x1202], 0), // strd r1, r2, [r0], #8
        ];
        for (code, n) in cases {
            let mut bench = ready(code, &[(n, DEVICE)]);
            bench.bus.fails_from = Some(u64::from(DEVICE) + 4);
            let before = bench.core.state.clone();
            assert_eq!(bench.run(1), (Exit::Returned, 0), "{code:04X?}");
            // The BusFault is taken before the run returns, and every register but the stack
            // pointer, which its frame moves, is as it was.
            assert_ne!(bench.core.state.ipsr, 0, "{code:04X?} took its fault");
            assert_eq!(bench.core.state.r[..13], before.r[..13], "{code:04X?}");
            // B1.5.10: the base is restored, so the frame sits where the stack pointer was.
            assert_eq!(bench.core.state.r[13], before.r[13] - 0x20, "{code:04X?}");
        }
    }

    /// B1.5.10 and B1.5.15: a load that faults inside an IT block is stacked with its own
    /// `ITSTATE`, which doesn't advance past it.
    #[test]
    fn a_load_that_faults_in_an_it_block_keeps_its_itstate() {
        // it eq, then ldreq r1, [r0, #4]!
        let mut bench = ready(&[0xBF08, 0xF850, 0x1F04], &[(0, DEVICE)]);
        bench.core.state.z = 1;
        bench.bus.fails_from = Some(u64::from(DEVICE) + 4);
        assert_eq!(bench.run(2), (Exit::Returned, 1));
        let mut stacked = State::default();
        stacked.set_xpsr(bench.word(bench.core.state.r[13] + 28));
        assert_eq!(stacked.it, 0x08, "ITSTATE 0x08, the LDR's own");
    }

    /// B1.4.7: whatever is loaded into SP, it keeps bits 1 and 0 clear.
    #[test]
    fn a_load_to_sp_keeps_it_word_aligned() {
        // ldr.w sp, [r2]
        let mut bench = ready(&[0xF8D2, 0xD000], &[(2, BASE)]);
        put(&mut bench, BASE, &[0x2000_1003]);
        run(&mut bench, 1);
        assert_eq!(bench.core.state.r[13], 0x2000_1000);
    }

    /// The UNPREDICTABLE writebacks to the register loaded, A7.7.42 and A7.7.45: Rt wins for
    /// LDR, which writes it last, and the writeback for LDRB, which writes it first.
    #[test]
    fn a_load_that_writes_back_to_its_own_register_does_what_its_pseudocode_does() {
        // ldr r2, [r2, #4]! then ldrb r2, [r2, #1]!
        for (code, r2) in [
            ([0xF852, 0x2F04], 0x8081_8283),
            ([0xF812, 0x2F01], BASE + 1),
        ] {
            let mut bench = ready(&code, &[(2, BASE)]);
            put(&mut bench, BASE, &[0x8081_8283, 0x8081_8283]);
            run(&mut bench, 1);
            assert_eq!(bench.core.state.r[2], r2, "{code:04X?}");
        }
        // ldm.w r0!, {r0, r1}: the base keeps what it loaded, A7.7.40.
        let mut bench = ready(&[0xE8B0, 0x0003], &[(0, BASE)]);
        put(&mut bench, BASE, &[0xA, 0xB]);
        run(&mut bench, 1);
        assert_eq!(bench.core.state.r[0..2], [0xA, 0xB]);
        // ldrd r1, r1, [r3]: the second word wins, A7.7.49.
        let mut bench = ready(&[0xE9D3, 0x1100], &[(3, BASE)]);
        put(&mut bench, BASE, &[0xA, 0xB]);
        run(&mut bench, 1);
        assert_eq!(bench.core.state.r[1], 0xB);
    }

    /// A list of no registers is UNPREDICTABLE, A7.7.40 and A7.7.156, and moves nothing, since
    /// the pseudocode's loop has nothing to do and its writeback adds nothing.
    #[test]
    fn an_empty_list_moves_nothing() {
        // ldm r0!, {} then stm r0!, {} then pop {} then push {}
        let mut bench = ready(&[0xC800, 0xC000, 0xBC00, 0xB400], &[(0, BASE), (13, BASE)]);
        let before = bench.core.state.clone();
        run(&mut bench, 4);
        assert_eq!(bench.core.state.r[..15], before.r[..15]);
        assert_eq!(words::<2>(&bench, BASE - 4), [0xA5A5_A5A5; 2]);
    }

    /// The UNPREDICTABLE stores, A7.7.158: a writeback to the register stored stores it as it
    /// was, and a store of the PC stores this instruction's address plus 4.
    #[test]
    fn a_store_of_its_own_base_or_the_pc_does_what_its_pseudocode_does() {
        // str r2, [r2, #4]! then str.w pc, [r2, #4]
        let mut bench = ready(&[0xF842, 0x2F04, 0xF8C2, 0xF004], &[(2, BASE)]);
        run(&mut bench, 1);
        assert_eq!(
            (bench.word(BASE + 4), bench.core.state.r[2]),
            (BASE, BASE + 4)
        );
        run(&mut bench, 1);
        assert_eq!(bench.word(BASE + 8), 4 + 4);
    }

    /// A3.2.1: LDM, STM, PUSH, POP, LDRD, STRD and the exclusives must be aligned whatever
    /// `CCR.UNALIGN_TRP` says, the rest only when it says so, TBH among them, and the T forms
    /// are checked as unprivileged.
    #[test]
    fn each_access_asks_for_the_alignment_and_privilege_a3_2_1_gives_it() {
        use Call::{Raise, Read, Write};
        let cases: [(&[u16], &[Call]); 14] = [
            (&[0xC803], &[Read(4, ALIGNED), Read(4, ALIGNED)]), // ldm r0, {r0, r1}
            (&[0xB408], &[Write(4, ALIGNED)]),                  // push {r3}
            (&[0xBC10], &[Read(4, ALIGNED)]),                   // pop {r4}
            (&[0xE9D3, 0x1202], &[Read(4, ALIGNED), Read(4, ALIGNED)]), // ldrd r1, r2, [r3]
            (&[0xE9C3, 0x1202], &[Write(4, ALIGNED), Write(4, ALIGNED)]), // strd r1, r2, [r3]
            (&[0xE8D2, 0x1F5F], &[Read(2, ALIGNED)]),           // ldrexh r1, [r2]
            (
                &[0xE842, 0x13FF],
                &[Raise(Fault::Unaligned as u32), Write(4, ALIGNED)],
            ), // strex
            (&[0xE8C2, 0x1F43], &[Write(1, ALIGNED)]),          // strexb r3, r1, [r2]
            (&[0xF85D, 0x4B04], &[Read(4, PLAIN)]),             // pop.w {r4}
            (&[0x5ED1], &[Read(2, PLAIN)]),                     // ldrsh r1, [r2, r3]
            (&[0xE8D1, 0xF012], &[Read(2, PLAIN)]),             // tbh [r1, r2, lsl #1]
            (&[0xF852, 0x1EFF], &[Read(4, UNPRIVILEGED)]),      // ldrt r1, [r2, #255]
            (&[0xF932, 0x1EFF], &[Read(2, UNPRIVILEGED)]),      // ldrsht r1, [r2, #255]
            (&[0xF802, 0x1EFF], &[Write(1, UNPRIVILEGED)]),     // strbt r1, [r2, #255]
        ];
        for (code, calls) in cases {
            assert_eq!(translated(code).as_deref(), Ok(calls), "{code:04X?}");
        }
    }

    /// The encodings the tables leave unallocated, and those A7.7 makes UNDEFINED.
    #[test]
    fn the_unallocated_encodings_are_undefined() {
        let undefined: [&[u16]; 30] = [
            &[0xE810, 0x0006], // Table A5-16, op 00
            &[0xE990, 0x0006], // Table A5-16, op 11
            &[0xE8C2, 0x1F63], // Table A5-17, op1 01, op2 00, op3 0110
            &[0xE8D2, 0x1F2F], // Table A5-17, op1 01, op2 01, op3 0010
            &[0xF952, 0x1004], // Table A5-18, op1 1x: no signed word
            &[0xF9DF, 0x1004], // Table A5-18, op1 1x with Rn PC
            &[0xF852, 0x1804], // A7.7.42 T4, P and W clear
            &[0xF832, 0x1A02], // A7.7.54 T3, P and W clear
            &[0xF852, 0x1040], // Table A5-18, op2 000001
            &[0xF812, 0x1100], // Table A5-20, op2 000100
            &[0xF862, 0x1004], // Table A5-21, op1 011
            &[0xF8E2, 0x1004], // Table A5-21, op1 111
            &[0xF842, 0x1040], // Table A5-21, op1 010, op2 000001
            &[0xF802, 0x1100], // Table A5-21, op1 000, op2 000100
            &[0xF822, 0x1200], // Table A5-21, op1 001, op2 001000
            &[0xF8CF, 0x1004], // A7.7.158 T3, Rn PC
            &[0xF84F, 0x1F04], // A7.7.158 T4, Rn PC: str r1, [pc, #4]!
            &[0xF842, 0x1804], // A7.7.158 T4, P and W clear
            &[0xF84F, 0x1003], // A7.7.159 T2, Rn PC
            &[0xF84F, 0x1E04], // A7.7.170 T1, Rn PC
            &[0xF88F, 0x1004], // A7.7.160 T2, Rn PC
            &[0xF80F, 0x1F01], // A7.7.160 T3, Rn PC: strb r1, [pc, #1]!
            &[0xF802, 0x1801], // A7.7.160 T3, P and W clear
            &[0xF80F, 0x1003], // A7.7.161 T2, Rn PC
            &[0xF80F, 0x1E04], // A7.7.162 T1, Rn PC
            &[0xF8AF, 0x1004], // A7.7.167 T2, Rn PC
            &[0xF82F, 0x1F02], // A7.7.167 T3, Rn PC: strh r1, [pc, #2]!
            &[0xF822, 0x1A02], // A7.7.167 T3, P and W clear
            &[0xF82F, 0x1003], // A7.7.168 T2, Rn PC
            &[0xF82F, 0x1E04], // A7.7.169 T1, Rn PC
        ];
        for code in undefined {
            assert_eq!(translated(code), Err(Undefined), "{code:04X?}");
        }
    }

    /// The UNPREDICTABLE encodings whose pseudocode would write the PC through `R[]`, which
    /// B1.4.7 never lets it, and which are UNDEFINED here.
    #[test]
    fn an_unpredictable_write_of_the_pc_through_r_is_undefined() {
        let undefined: [&[u16]; 12] = [
            &[0xF852, 0xFEFF], // ldrt pc, [r2, #255]
            &[0xF812, 0xFF01], // ldrb pc, [r2, #1]!, Table A5-20
            &[0xF832, 0xF902], // ldrh pc, [r2], #-2, Table A5-19
            &[0xF932, 0xFEFF], // ldrsht pc, [r2, #255]
            &[0xE852, 0xFFFF], // ldrex pc, [r2, #1020]
            &[0xE842, 0x1FFF], // strex pc, r1, [r2, #1020]
            &[0xE9D3, 0xF2FF], // ldrd pc, r2, [r3, #1020]
            &[0xE9D3, 0x1FFF], // ldrd r1, pc, [r3, #1020]
            &[0xE9EF, 0x1202], // strd r1, r2, [pc, #8]!
            &[0xE86F, 0x1202], // strd r1, r2, [pc], #-8
            &[0xE8BF, 0x0006], // ldm.w pc!, {r1, r2}
            &[0xE8AF, 0x0006], // stm.w pc!, {r1, r2}
        ];
        for code in undefined {
            assert_eq!(translated(code), Err(Undefined), "{code:04X?}");
        }
    }
}