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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Branches, IT, hints and the system instructions, DDI 0403E.b A5.2.5, A5.2.6, A5.3.4 and B5.2.
//!
//! Where the manual calls an encoding UNPREDICTABLE, it runs as the pseudocode reads without that
//! line, the simplest thing the pseudocode suggests. In an IT block that means B encodings T1 and
//! T3 test only their own condition, A7.3.1's `CurrentCond()`, and CBZ, CBNZ, CPS and IT test
//! none, since their operations never call `ConditionPassed()`. B encodings T2 and T4 and BL test
//! the block's condition wherever they sit in it, and a taken one leaves `ITSTATE` advanced, since
//! `BranchWritePC()` doesn't touch it. IT with `firstcond` 1111, or 1110 and an else, runs every
//! instruction it covers. `CPS` with neither mask changes nothing, and `MRS` of a special register
//! v7-M doesn't have reads zero. `MRS` to SP writes it as `R[13]` does, bits 1 and 0 clear. `MRS`
//! to the PC can't run that way, since `R[]` never writes the PC, B1.4.7, so it's UNDEFINED. `MSR`
//! from SP or the PC writes what `R[n]` reads, `MSR` of mask 00 to the APSR writes nothing, `MSR`
//! to any other register writes it whatever the mask, since its operation never reads the mask
//! there, `MSR` of GE on a core without the DSP extension writes nothing, and `MSR` to a register
//! v7-M doesn't have changes nothing. Bits the diagrams mark (0) or (1) aren't checked, A5.1.1.

use std::mem::offset_of;

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

use super::super::family::Family;
use super::super::registers::{control, get, mask, masks, set, xpsr};
use super::super::state::State;
use super::{Emitter, Fault, Instruction, Translated, Undefined, bits};

/// `APSR`'s N, Z, C, V and Q, and GE, in `xPSR`, B1.4.2.
const APSR: u32 = APSR_NZCVQ | mask(xpsr::GE);
/// The APSR without GE, which only the DSP extension has, B5.2.2.
const APSR_NZCVQ: u32 =
    mask(xpsr::N) | mask(xpsr::Z) | mask(xpsr::C) | mask(xpsr::V) | mask(xpsr::Q);

/// Whether an IT block's condition leaves `instruction` alone. B encodings T1 and T3 test their own
/// condition, A7.3.1, and BKPT, CBZ, CBNZ, CPS and IT test none, A7.7.17, A7.7.21, B5.2.1 and
/// A7.7.37. UDF and SVC in B T1's space still test the block's, A7.3.2 and A7.7.175.
pub(super) fn ignores_it_condition(instruction: Instruction) -> bool {
    match instruction {
        Instruction::Narrow(hw) => {
            let hw = u32::from(hw);
            match bits(hw, 15, 12) {
                0b1101 => bits(hw, 11, 9) != 0b111,
                0b1011 => {
                    let op = bits(hw, 11, 8);
                    op == 0b1110
                        || op & 0b0101 == 0b0001
                        || bits(hw, 11, 5) == 0b011_0011
                        || (op == 0b1111 && bits(hw, 3, 0) != 0)
                }
                _ => false,
            }
        }
        Instruction::Wide(hw1, hw2) => {
            let (hw1, hw2) = (u32::from(hw1), u32::from(hw2));
            bits(hw1, 15, 11) == 0b11110
                && bits(hw2, 15, 14) == 0b10
                && bits(hw2, 12, 12) == 0
                && bits(hw1, 9, 7) != 0b111
        }
    }
}

/// A5.2.6, conditional branch and supervisor call, Table A5-8.
pub(super) fn conditional_branch_supervisor_call(e: &mut Emitter<'_, '_>, hw: u16) -> Translated {
    let hw = u32::from(hw);
    match bits(hw, 11, 8) {
        // UDF, A7.7.191 encoding T1.
        0b1110 => Err(Undefined),
        // SVC, A7.7.175.
        0b1111 => {
            e.raise(Fault::SupervisorCall);
            Ok(())
        }
        // B, A7.7.12 encoding T1.
        cond => {
            let target = relative(e, sign_extend(bits(hw, 7, 0) << 1, 9));
            let holds = e.condition(cond);
            e.branch_if(holds, target);
            Ok(())
        }
    }
}

/// B, A7.7.12 encoding T2.
pub(super) fn branch16(e: &mut Emitter<'_, '_>, hw: u16) {
    let target = relative(e, sign_extend(bits(u32::from(hw), 10, 0) << 1, 12));
    e.branch_to(target);
}

/// CPS, B5.2.1.
pub(super) fn change_processor_state(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let affected = bits(hw, 1, 0);
    // UNPREDICTABLE, and the operation touches neither mask.
    if affected == 0 {
        return;
    }
    let disable = e.constant(bits(hw, 4, 4));
    let affected = e.constant(affected);
    e.call_plain(change_masks as *const () as usize, &[disable, affected]);
    e.end_block();
}

/// CBNZ and CBZ, A7.7.21.
pub(super) fn compare_branch(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let imm32 = (bits(hw, 9, 9) << 6) | (bits(hw, 7, 3) << 1);
    let value = e.reg(bits(hw, 2, 0));
    let taken = if bits(hw, 11, 11) == 1 {
        IntCC::NotEqual
    } else {
        IntCC::Equal
    };
    let holds = e.b.ins().icmp_imm_s(taken, value, 0);
    let target = relative(e, imm32);
    e.branch_if(holds, target);
}

/// BKPT, A7.7.17, whose `imm8` the processor ignores and a debugger reads. Arm's semihosting
/// specification, "The semihosting interface", gives `BKPT #0xAB` as the M profile's trap for a
/// semihosting call.
pub(super) fn breakpoint(e: &mut Emitter<'_, '_>, hw: u16) {
    if bits(u32::from(hw), 7, 0) == SEMIHOSTING_TRAP {
        e.raise(Fault::HostCall);
    } else {
        e.raise(Fault::Breakpoint);
    }
}

/// The `imm8` of `BKPT` that traps for a semihosting call.
const SEMIHOSTING_TRAP: u32 = 0xAB;

/// A5.2.5's If-Then and hints, Table A5-7.
pub(super) fn if_then_hints(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    if bits(hw, 3, 0) == 0 {
        hint(e, bits(hw, 7, 4));
    } else {
        // IT, A7.7.37.
        e.set_next_it(bits(hw, 7, 0));
    }
}

/// A5.3.4, branches and miscellaneous control, Table A5-13.
pub(super) fn branches_miscellaneous_control(
    e: &mut Emitter<'_, '_>,
    hw1: u16,
    hw2: u16,
) -> Translated {
    let (hw1, hw2) = (u32::from(hw1), u32::from(hw2));
    let op = bits(hw1, 10, 4);
    match bits(hw2, 14, 12) {
        0b000 | 0b010 => match op {
            // B, A7.7.12 encoding T3.
            _ if op & 0b011_1000 != 0b011_1000 => {
                let imm = (bits(hw1, 10, 10) << 20)
                    | (bits(hw2, 11, 11) << 19)
                    | (bits(hw2, 13, 13) << 18)
                    | (bits(hw1, 5, 0) << 12)
                    | (bits(hw2, 10, 0) << 1);
                let target = relative(e, sign_extend(imm, 21));
                let holds = e.condition(bits(hw1, 9, 6));
                e.branch_if(holds, target);
                Ok(())
            }
            0b011_1000 | 0b011_1001 => {
                move_to_special(e, hw1, hw2);
                Ok(())
            }
            // Table A5-14. Its op1 other than 000 is the other profiles' 32-bit CPS.
            0b011_1010 if bits(hw2, 10, 8) == 0 => {
                hint(e, bits(hw2, 7, 0));
                Ok(())
            }
            0b011_1011 => miscellaneous_control(e, hw2),
            0b011_1110 | 0b011_1111 => move_from_special(e, hw2),
            // UDF encoding T2, A7.7.191, is among these.
            _ => Err(Undefined),
        },
        // B, A7.7.12 encoding T4.
        0b001 | 0b011 => {
            let target = relative(e, long_offset(hw1, hw2));
            e.branch_to(target);
            Ok(())
        }
        // BL, A7.7.18.
        0b101 | 0b111 => {
            let target = relative(e, long_offset(hw1, hw2));
            let link = e.constant(e.next_pc() | 1);
            e.set_reg(14, link);
            e.branch_to(target);
            Ok(())
        }
        _ => Err(Undefined),
    }
}

/// The hints of Tables A5-7 and A5-14 by number. The unallocated ones run as NOP, as both tables
/// say, and so does DBG, A7.7.31, since nothing here traces.
fn hint(e: &mut Emitter<'_, '_>, op: u32) {
    match op {
        // WFE, A7.7.258. Whether it waits is the event register's, which `Family::sleep` reads.
        0b0010 => e.wait(true),
        // WFI, A7.7.259.
        0b0011 => e.wait(false),
        // SEV, A7.7.127. This processor is one of those it signals, B1.5.18.
        0b0100 => {
            let one = e.constant(1);
            e.store_field(offset_of!(State, event), one);
        }
        // NOP, A7.7.87, and YIELD, A7.7.260, since nothing here runs another thread.
        _ => {}
    }
}

/// The miscellaneous control instructions, Table A5-15.
fn miscellaneous_control(e: &mut Emitter<'_, '_>, hw2: u32) -> Translated {
    match bits(hw2, 7, 4) {
        // CLREX, A7.7.23, with the local monitor the only one, A3.4.
        0b0010 => super::memory::clear_exclusive(e),
        // DSB, A7.7.33, and DMB, A7.7.32. Every access completes before the next instruction
        // starts here, so there's nothing to wait for.
        0b0100 | 0b0101 => {}
        // ISB, A7.7.36. What the next instruction's translation depends on may have changed.
        0b0110 => e.end_block(),
        _ => return Err(Undefined),
    }
    Ok(())
}

/// MRS, A7.7.81 and B5.2.2.
fn move_from_special(e: &mut Emitter<'_, '_>, hw2: u32) -> Translated {
    let d = bits(hw2, 11, 8);
    if d == 15 {
        return Err(Undefined);
    }
    let sysm = bits(hw2, 7, 0);
    let which = e.constant(sysm);
    let read = read_special as *const () as usize;
    // Only the APSR's views read the flags, and only the stack pointers read `R13`.
    let value = if sysm >> 3 < 0b00010 {
        e.call(read, &[which])
    } else {
        e.call_plain(read, &[which])
    };
    // B1.4.7: `R[13]` keeps bits 1 and 0 clear.
    let value = if d == 13 {
        e.b.ins().band_imm_s(value, !3)
    } else {
        value
    };
    e.set_reg(d, value);
    Ok(())
}

/// MSR, A7.7.82 and B5.2.3.
fn move_to_special(e: &mut Emitter<'_, '_>, hw1: u32, hw2: u32) {
    let sysm = bits(hw2, 7, 0);
    let value = e.reg(bits(hw1, 3, 0));
    let which = e.constant((bits(hw2, 11, 10) << 8) | sysm);
    let write = write_special as *const () as usize;
    // The masks can skip `call`'s write back because they touch no register or flag. The APSR
    // touches the flags, and the stack pointers and `CONTROL` touch `R13`.
    if (16..=19).contains(&sysm) {
        e.call_plain(write, &[which, value]);
    } else {
        e.call(write, &[which, value]);
    }
    // The next instruction's translation, and which exception preempts, hang on these.
    if matches!(sysm >> 3, 0b00001 | 0b00010) {
        e.end_block();
    }
}

/// `PC + imm32` for a branch, with the PC reading as the instruction's address plus 4, A2.3.1.
fn relative(e: &Emitter<'_, '_>, imm32: u32) -> u32 {
    e.pc().wrapping_add(4).wrapping_add(imm32)
}

/// `SignExtend(value, 32)` of a `width`-bit value.
fn sign_extend(value: u32, width: u32) -> u32 {
    let above = 32 - width;
    ((value << above).cast_signed() >> above).cast_unsigned()
}

/// `SignExtend(S:I1:I2:imm10:imm11:'0', 32)`, where `I1 = NOT(J1 EOR S)` and
/// `I2 = NOT(J2 EOR S)`, A7.7.12 encoding T4 and A7.7.18.
fn long_offset(hw1: u32, hw2: u32) -> u32 {
    let s = bits(hw1, 10, 10);
    let i1 = !(bits(hw2, 13, 13) ^ s) & 1;
    let i2 = !(bits(hw2, 11, 11) ^ s) & 1;
    let imm =
        (s << 24) | (i1 << 23) | (i2 << 22) | (bits(hw1, 9, 0) << 12) | (bits(hw2, 10, 0) << 1);
    sign_extend(imm, 25)
}

/// `CPS`'s operation, B5.2.1: `disable` is 1 for CPSID and 0 for CPSIE, and `affected` has bit 1
/// for `PRIMASK` and bit 0 for `FAULTMASK`.
extern "C" fn change_masks(core: &mut Family, disable: u32, affected: u32) -> u32 {
    if !core.state.privileged() {
        return 0;
    }
    let faultmask = affected & 0b01 != 0 && (disable == 0 || !core.below_priority_zero());
    if affected & 0b10 != 0 {
        core.state.primask = disable;
    }
    if faultmask {
        core.state.faultmask = disable;
    }
    0
}

/// What `MRS` reads of the special register `sysm` names, B5.2.2 and Table B5-1.
extern "C" fn read_special(core: &mut Family, sysm: u32) -> u32 {
    let state = &core.state;
    let privileged = state.privileged();
    match (sysm >> 3, sysm & 0b111) {
        (0b00000, low) => {
            let ipsr = if low & 0b001 == 0 { 0 } else { state.ipsr };
            // EPSR reads as zero, and GE reads with the flags only with the DSP extension.
            let apsr = if low & 0b100 != 0 {
                0
            } else if core.features.dsp {
                state.xpsr() & APSR
            } else {
                state.xpsr() & APSR_NZCVQ
            };
            ipsr | apsr
        }
        (0b00001, 0b000) if privileged => state.msp(),
        (0b00001, 0b001) if privileged => state.psp(),
        (0b00010, 0b000) if privileged => get(masks::PM, state.primask),
        (0b00010, 0b001 | 0b010) if privileged => u32::from(core.scs.basepri()),
        (0b00010, 0b011) if privileged => get(masks::FM, state.faultmask),
        (0b00010, 0b100) => state.control & core.features.control(),
        _ => 0,
    }
}

/// `BASEPRI`'s field of `value`, B1.4.3.
fn basepri(value: u32) -> u8 {
    u8::try_from(get(masks::BASEPRI, value)).expect("eight bits")
}

/// What `MSR` writes of `value` to the special register `sysm` names, in the low byte of `which`,
/// with the APSR's `mask` in bits 9 and 8, B5.2.3 and Table B5-2.
extern "C" fn write_special(core: &mut Family, which: u32, value: u32) -> u32 {
    let (mask, sysm) = (bits(which, 9, 8), bits(which, 7, 0));
    let privileged = core.state.privileged();
    let above_hard_fault = !core.below_priority_zero();
    let features = core.features;
    let state = &mut core.state;
    match (sysm >> 3, sysm & 0b111) {
        (0b00000, low) if low & 0b100 == 0 => {
            // Without the DSP extension, a write of GE is UNPREDICTABLE and writes nothing.
            if mask & 0b01 != 0 && features.dsp {
                state.ge = get(xpsr::GE, value);
            }
            if mask & 0b10 != 0 {
                state.n = get(xpsr::N, value);
                state.z = get(xpsr::Z, value);
                state.c = get(xpsr::C, value);
                state.v = get(xpsr::V, value);
                state.q = get(xpsr::Q, value);
            }
        }
        // B1.4.1: a stack pointer's bits 1 and 0 are RAZ/WI.
        (0b00001, 0b000) if privileged => state.set_msp(value),
        (0b00001, 0b001) if privileged => state.set_psp(value),
        (0b00010, 0b000) if privileged => state.primask = get(masks::PM, value),
        (0b00010, 0b001) if privileged => core.scs.write_basepri(basepri(value)),
        // BASEPRI_MAX only ever raises the priority BASEPRI masks at.
        (0b00010, 0b010) if privileged => {
            let (asked, held) = (get(masks::BASEPRI, value), u32::from(core.scs.basepri()));
            if asked != 0 && (asked < held || held == 0) {
                core.scs.write_basepri(basepri(value));
            }
        }
        (0b00010, 0b011) if privileged && above_hard_fault => {
            state.faultmask = get(masks::FM, value);
        }
        (0b00010, 0b100) if privileged => {
            let mut written = features.control();
            if state.handler() {
                written = set(control::SPSEL, written, 0);
            }
            let control = (state.control & !written) | (value & written);
            state.set_mode(state.ipsr, control);
        }
        _ => {}
    }
    0
}

#[cfg(test)]
mod tests {
    //! Each encoding runs on a [`Bench`] and is checked by what it leaves in the processor. What
    //! faults is only translated, since the exception model takes it from there.

    use cranelift_codegen::ir::{self, types};
    use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};

    use super::super::super::scs::exception::{HARD_FAULT, NMI};
    use super::super::testing::spec_of;
    use super::super::testing::{Bench, CODE};
    use super::super::{decode16, decode32, emit_one};
    use super::*;
    use crate::emulator::Exit;
    use crate::machine::armv7m::{Fpu, MpuRegions, Variant};

    /// The `APSR` masks built from the field table are B1.4.2's, read off the page: N, Z, C, V
    /// and Q, and those with GE.
    #[test]
    fn the_apsr_masks_are_the_manuals() {
        assert_eq!(APSR_NZCVQ, 0xF800_0000);
        assert_eq!(APSR, 0xF80F_0000);
    }

    /// `MRS Rd, <spec_reg>`, A7.7.81.
    fn mrs(d: u16, sysm: u16) -> [u16; 2] {
        [0xF3EF, 0x8000 | (d << 8) | sysm]
    }

    /// `MSR <spec_reg>, Rn`, A7.7.82.
    fn msr(n: u16, mask: u16, sysm: u16) -> [u16; 2] {
        [0xF380 | n, 0x8000 | (mask << 10) | sysm]
    }

    const IPSR: u16 = 5;
    const MSP: u16 = 8;
    const PSP: u16 = 9;
    const PRIMASK: u16 = 16;
    const BASEPRI: u16 = 17;
    const BASEPRI_MAX: u16 = 18;
    const FAULTMASK: u16 = 19;
    const CONTROL: u16 = 20;

    /// A bench that's run `code` from [`CODE`] after `prepare`, `instructions` of it, and how it
    /// stopped. Every instruction asked for must retire.
    fn after(code: &[u16], instructions: u32, prepare: impl FnOnce(&mut Family)) -> (Bench, Exit) {
        let mut bench = Bench::new(code);
        prepare(&mut bench.core);
        let (exit, ran) = bench.run(instructions);
        assert_eq!(ran, u64::from(instructions), "every instruction retires");
        (bench, exit)
    }

    /// The state after `code` ran `instructions` from `prepare`.
    fn state(code: &[u16], instructions: u32, prepare: impl FnOnce(&mut Family)) -> State {
        after(code, instructions, prepare).0.core.state.clone()
    }

    /// Where `code` goes next after one instruction from `prepare`.
    fn next(code: &[u16], prepare: impl FnOnce(&mut Family)) -> u32 {
        state(code, 1, prepare).r[15]
    }

    /// One instruction at [`CODE`] with `ITSTATE` `it`, lowered by `lower` and never run: what
    /// `lower` answered, whether the instruction ended the block, and the function so far.
    fn lowered<T>(
        halfwords: &[u16],
        it: u32,
        lower: impl FnOnce(&mut Emitter<'_, '_>, Instruction) -> T,
    ) -> (T, bool, ir::Function) {
        let instruction = match *halfwords {
            [hw] => Instruction::Narrow(hw),
            [hw1, hw2] => Instruction::Wide(hw1, hw2),
            _ => panic!("an instruction is one or two halfwords"),
        };
        let mut function = ir::Function::new();
        function
            .signature
            .params
            .push(ir::AbiParam::new(types::I64));
        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, instruction.length(), it);
        let answer = lower(&mut e, instruction);
        let ended = e.ended();
        (answer, ended, function)
    }

    /// What the decoder answers for one instruction, and whether it ended the block.
    fn decoded(halfwords: &[u16], it: u32) -> (Translated, bool) {
        let (answer, ended, _) = lowered(halfwords, it, |e, instruction| match instruction {
            Instruction::Narrow(hw) => decode16(e, hw),
            Instruction::Wide(hw1, hw2) => decode32(e, hw1, hw2),
        });
        (answer, ended)
    }

    /// How many ways out of the block one instruction has, IT condition and all.
    fn exits(halfwords: &[u16], it: u32) -> usize {
        let ((), _, function) = lowered(halfwords, it, emit_one);
        super::super::exits_of(&function)
    }

    /// `number` active and being handled, as the exception model leaves it once it's taken.
    fn handling(core: &mut Family, number: u16) {
        core.scs.pend(number);
        assert_eq!(core.scs.acknowledge(core.masks()), Some(number));
        core.state.ipsr = u32::from(number);
    }

    fn undefined(halfwords: &[u16]) -> bool {
        decoded(halfwords, 0).0 == Err(Undefined)
    }

    /// The processor in unprivileged Thread mode, B1.4.4.
    fn unprivileged(core: &mut Family) {
        core.state.control = mask(control::NPRIV);
    }

    /// A7.7.12 encoding T1: `PC + SignExtend(imm8:'0')` when the condition holds, the next
    /// instruction when it doesn't.
    #[test]
    fn b_t1_branches_when_its_condition_holds() {
        assert_eq!(next(&[0xD002], |core| core.state.z = 1), 8);
        assert_eq!(next(&[0xD002], |core| core.state.z = 0), 2);
        let mut bench = Bench::new(&[]);
        bench.place(0x100, &[0xD1FC]);
        bench.core.state.r[15] = 0x100;
        bench.run(1);
        assert_eq!(bench.core.state.r[15], 0xFC, "backwards when it's negative");
    }

    /// A branch to itself retires once and waits for an interrupt as `WFI` does, so the clock
    /// warps through the spin rather than counting it.
    #[test]
    fn b_t1_to_itself_waits_for_an_interrupt() {
        let mut bench = Bench::new(&[0xD0FE]);
        bench.core.state.z = 1;
        assert_eq!(bench.run(10), (Exit::Waiting, 1));
        assert_eq!(bench.core.state.r[15], CODE);
    }

    /// Table A5-8: cond 1110 is UDF and 1111 is SVC, which ends the block and retires.
    #[test]
    fn udf_and_svc_take_the_conditional_branch_space_of_al_and_nv() {
        assert!(undefined(&[0xDE00]));
        assert!(undefined(&[0xDEFF]));
        assert_eq!(decoded(&[0xDF05], 0), (Ok(()), true));
        after(&[0xDF05], 1, |_| {});
    }

    /// A7.7.12 encoding T2 reaches 2046 bytes forward and 2048 back.
    #[test]
    fn b_t2_reaches_both_ends_of_its_range() {
        assert_eq!(next(&[0xE3FF], |_| {}), 0x802);
        let mut bench = Bench::new(&[]);
        bench.place(0x1000, &[0xE400]);
        bench.core.state.r[15] = 0x1000;
        bench.run(1);
        assert_eq!(bench.core.state.r[15], 0x804);
    }

    /// Encoding T2 is allowed last in an IT block, and runs under its condition there.
    #[test]
    fn b_t2_last_in_an_it_block_runs_under_its_condition() {
        let code = [0xBF18, 0xE002];
        assert_eq!(state(&code, 2, |core| core.state.z = 1).r[15], 4);
        assert_eq!(state(&code, 2, |core| core.state.z = 0).r[15], 10);
    }

    /// A7.7.21: CBZ branches on zero and CBNZ on anything else, forward by `i:imm5:'0'` up to 126,
    /// and neither touches a flag.
    #[test]
    fn cbz_and_cbnz_branch_forward_on_zero_and_nonzero() {
        let flags = |core: &mut Family| {
            core.state.n = 1;
            core.state.c = 1;
        };
        assert_eq!(next(&[0xB100], flags), 4);
        assert_eq!(
            next(&[0xB100], |core| {
                flags(core);
                core.state.r[0] = 1;
            }),
            2
        );
        let taken = state(&[0xBBF9], 1, |core| {
            flags(core);
            core.state.r[1] = 5;
        });
        assert_eq!(taken.r[15], 4 + 126);
        assert_eq!(
            (taken.n, taken.z, taken.c, taken.v),
            (1, 0, 1, 0),
            "the flags stay"
        );
        assert_eq!(next(&[0xBBF9], |_| {}), 2);
    }

    /// CBZ is UNPREDICTABLE inside an IT block, and runs as its pseudocode reads, which never
    /// tests the block's condition, A7.7.21.
    #[test]
    fn cbz_inside_an_it_block_ignores_the_blocks_condition() {
        let code = [0xBF08, 0xB108];
        assert_eq!(state(&code, 2, |core| core.state.z = 1).r[15], 8);
        assert_eq!(state(&code, 2, |core| core.state.z = 0).r[15], 8);
        let nonzero = state(&code, 2, |core| {
            core.state.z = 1;
            core.state.r[0] = 1;
        });
        assert_eq!(nonzero.r[15], 4);
    }

    /// CBNZ is UNPREDICTABLE inside an IT block too, and branches on its register whatever the
    /// block's condition, A7.7.21.
    #[test]
    fn cbnz_inside_an_it_block_ignores_the_blocks_condition() {
        let code = [0xBF08, 0xB908];
        for z in [0, 1] {
            let nonzero = state(&code, 2, |core| {
                core.state.z = z;
                core.state.r[0] = 1;
            });
            assert_eq!(nonzero.r[15], 8, "Z {z}");
            assert_eq!(state(&code, 2, |core| core.state.z = z).r[15], 4, "Z {z}");
        }
    }

    /// B encodings T1 and T3 are UNPREDICTABLE inside an IT block, A7.7.12, and test only their own
    /// condition there, A7.3.1's `CurrentCond()`.
    #[test]
    fn b_t1_and_t3_inside_an_it_block_test_only_their_own_condition() {
        for (code, fallthrough) in [(&[0xBF08, 0xD102][..], 4), (&[0xBF08, 0xF040, 0x8002], 6)] {
            assert_eq!(
                state(code, 2, |core| core.state.z = 0).r[15],
                10,
                "{code:04x?}"
            );
            assert_eq!(
                state(code, 2, |core| core.state.z = 1).r[15],
                fallthrough,
                "{code:04x?}"
            );
        }
    }

    /// A7.3.2: UDF whose IT condition fails is a NOP, so B T1's UDF space still tests the block's
    /// condition, and so does UDF encoding T2.
    #[test]
    fn udf_whose_it_condition_fails_is_a_nop() {
        let ran = state(&[0xBF08, 0xDE00], 2, |_| {});
        assert_eq!((ran.r[15], ran.it), (4, 0));
        let ran = state(&[0xBF08, 0xF7F0, 0xA000], 2, |_| {});
        assert_eq!((ran.r[15], ran.it), (6, 0));
    }

    /// B encodings T2 and T4 and BL are UNPREDICTABLE in an IT block but not last, A7.7.12 and
    /// A7.7.18. They test the block's condition, and a taken one leaves `ITSTATE` advanced, since
    /// `BranchWritePC()` doesn't touch it.
    #[test]
    fn b_t2_t4_and_bl_inside_an_it_block_but_not_last_run_under_its_condition() {
        for (code, fallthrough) in [
            (&[0xBF04, 0xE002][..], 4),
            (&[0xBF04, 0xF000, 0xB802], 6),
            (&[0xBF04, 0xF000, 0xF802], 6),
        ] {
            let taken = state(code, 2, |core| core.state.z = 1);
            assert_eq!((taken.r[15], taken.it), (10, 0x08), "{code:04x?}");
            let skipped = state(code, 2, |core| core.state.r[14] = 0xEEEE);
            assert_eq!(
                (skipped.r[15], skipped.it, skipped.r[14]),
                (fallthrough, 0x08, 0xEEEE),
                "{code:04x?}"
            );
        }
        assert_eq!(
            state(&[0xBF04, 0xF000, 0xF802], 2, |core| core.state.z = 1).r[14],
            7
        );
    }

    /// CPS is UNPREDICTABLE inside an IT block, and its operation never tests the block's
    /// condition, B5.2.1.
    #[test]
    fn cps_inside_an_it_block_ignores_the_blocks_condition() {
        let code = [0xBF08, 0xB672];
        assert_eq!(state(&code, 2, |core| core.state.z = 0).primask, 1);
        assert_eq!(state(&code, 2, |core| core.state.z = 1).primask, 1);
    }

    /// B5.2.1: CPSID sets and CPSIE clears the masks `I` and `F` name.
    #[test]
    fn cps_sets_and_clears_primask_and_faultmask() {
        let masks = |state: State| (state.primask, state.faultmask);
        assert_eq!(masks(state(&[0xB672], 1, |_| {})), (1, 0));
        assert_eq!(masks(state(&[0xB671], 1, |_| {})), (0, 1));
        assert_eq!(masks(state(&[0xB673], 1, |_| {})), (1, 1));
        let both = |core: &mut Family| {
            core.state.primask = 1;
            core.state.faultmask = 1;
        };
        assert_eq!(masks(state(&[0xB662], 1, both)), (0, 1));
        assert_eq!(masks(state(&[0xB661], 1, both)), (1, 0));
        assert_eq!(masks(state(&[0xB663], 1, both)), (0, 0));
    }

    /// Unprivileged code can't change a mask, and HardFault and NMI can't set `FAULTMASK`, since
    /// their execution priority isn't above -1. They can still clear it.
    #[test]
    fn cps_respects_privilege_and_the_execution_priority() {
        let masks = |state: State| (state.primask, state.faultmask);
        assert_eq!(masks(state(&[0xB673], 1, unprivileged)), (0, 0));
        for number in [NMI, HARD_FAULT] {
            let handler = |core: &mut Family| handling(core, number);
            assert_eq!(masks(state(&[0xB673], 1, handler)), (1, 0));
            let set = |core: &mut Family| {
                handler(core);
                core.state.faultmask = 1;
            };
            assert_eq!(masks(state(&[0xB661], 1, set)), (0, 0));
        }
        let svcall = |core: &mut Family| core.state.ipsr = 11;
        assert_eq!(masks(state(&[0xB671], 1, svcall)), (0, 1));
    }

    /// CPS with neither `I` nor `F` is UNPREDICTABLE, B5.2.1, and changes nothing.
    #[test]
    fn cps_with_neither_mask_changes_nothing() {
        let mut expected = Bench::new(&[]).core.state.clone();
        expected.r[15] = 2;
        assert_eq!(state(&[0xB670], 1, |_| {}), expected);
        let both = |core: &mut Family| {
            core.state.primask = 1;
            core.state.faultmask = 1;
        };
        assert_eq!(state(&[0xB660], 1, both).primask, 1);
    }

    /// A7.7.17: BKPT raises its debug event, which leaves before the instruction retires.
    #[test]
    fn bkpt_raises_and_ends_the_block() {
        assert_eq!(decoded(&[0xBE00], 0), (Ok(()), true));
        assert_eq!(decoded(&[0xBEAB], 0), (Ok(()), true));
    }

    /// A7.7.17: BKPT is unconditional inside an IT block too, so its one way out is the raise,
    /// where SVC under the same block has two of its own, retired or locked up, B1.5.15, and the
    /// way past it its failed condition takes.
    #[test]
    fn bkpt_inside_an_it_block_raises_whatever_the_condition() {
        assert_eq!(exits(&[0xBE00], 0), 1);
        assert_eq!(exits(&[0xBE00], 0x08), 1);
        assert_eq!(exits(&[0xBE00], 0x14), 1);
        assert_eq!(exits(&[0xDF00], 0x08), 3);
    }

    /// A7.7.37: `ITSTATE` becomes `firstcond:mask` for the next instruction.
    #[test]
    fn it_sets_itstate_for_the_instructions_after_it() {
        let after_it = state(&[0xBF0C], 1, |_| {});
        assert_eq!(after_it.it, 0x0C);
        assert_eq!(after_it.r[15], 2);
        assert_eq!(decoded(&[0xBF0C], 0), (Ok(()), false));
    }

    /// ITE EQ runs the first instruction when Z is set and the second when it isn't, and the
    /// block goes on past it unconditionally.
    #[test]
    fn an_it_block_runs_each_instruction_under_its_condition() {
        let [a, b] = mrs(0, 0);
        let [c, d] = mrs(1, 0);
        let [f, g] = mrs(2, 0);
        let code = [0xBF0C, a, b, c, d, f, g];
        let preset = |core: &mut Family, z: u32| {
            core.state.z = z;
            core.state.r[0] = 0xAAAA;
            core.state.r[1] = 0xBBBB;
            core.state.r[2] = 0xCCCC;
        };
        let equal = state(&code, 4, |core| preset(core, 1));
        assert_eq!(
            equal.r[..3],
            [0x4000_0000, 0xBBBB, 0x4000_0000],
            "the then runs"
        );
        assert_eq!(equal.it, 0);
        let unequal = state(&code, 4, |core| preset(core, 0));
        assert_eq!(unequal.r[..3], [0xAAAA, 0, 0], "the else runs");
        assert_eq!(unequal.r[15], 14);
    }

    /// IT inside an IT block is UNPREDICTABLE. Its operation never tests the outer block's
    /// condition, so it sets `ITSTATE` whether that holds or not, A7.7.37.
    #[test]
    fn it_inside_an_it_block_sets_itstate_whatever_the_outer_condition() {
        let [a, b] = mrs(0, 0);
        let code = [0xBF08, 0xBF18, a, b];
        let preset = |core: &mut Family, z: u32| {
            core.state.z = z;
            core.state.n = 1;
            core.state.r[0] = 0xAAAA;
        };
        assert_eq!(state(&code, 2, |core| preset(core, 0)).it, 0x18);
        assert_eq!(state(&code, 2, |core| preset(core, 1)).it, 0x18);
        assert_eq!(state(&code, 3, |core| preset(core, 0)).r[0], 0x8000_0000);
        assert_eq!(state(&code, 3, |core| preset(core, 1)).r[0], 0xAAAA);
    }

    /// IT with `firstcond` 1111, or 1110 and more than one mask bit, is UNPREDICTABLE, A7.7.37,
    /// and every condition it gives runs as always, A7.3.1's `ConditionPassed()` for 111x.
    #[test]
    fn it_of_al_with_an_else_runs_every_instruction() {
        let mut code = vec![0];
        for d in 0..4 {
            code.extend(mrs(d, 0));
        }
        for it in [0xBFEC, 0xBFE6, 0xBFE3, 0xBFEA, 0xBFEF, 0xBFF4] {
            code[0] = it;
            let ran = state(&code, 5, |core| {
                core.state.c = 1;
                core.state.r[..4].fill(7);
            });
            assert_eq!(ran.r[..4], [0x2000_0000; 4], "{it:#06x}");
        }
    }

    /// NOP, YIELD, DBG and the unallocated hints of both widths retire and change nothing else,
    /// Tables A5-7 and A5-14.
    #[test]
    fn nop_yield_dbg_and_the_unallocated_hints_change_nothing() {
        let code = [
            0xBF00, 0xBF10, 0xBF50, 0xBFF0, 0xF3AF, 0x8000, 0xF3AF, 0x8001, 0xF3AF, 0x80F3, 0xF3AF,
            0x8005, 0xF3AF, 0x80EF,
        ];
        let mut expected = Bench::new(&[]).core.state.clone();
        expected.r[15] = 28;
        assert_eq!(state(&code, 9, |_| {}), expected);
    }

    /// A7.7.259: WFI retires and leaves the processor waiting, in both widths.
    #[test]
    fn wfi_waits_for_an_interrupt() {
        for (code, length) in [(&[0xBF30][..], 2), (&[0xF3AF, 0x8003][..], 4)] {
            let (bench, exit) = after(code, 1, |_| {});
            assert_eq!(exit, Exit::Waiting);
            assert_eq!(bench.core.state.sleeping, 1);
            assert_eq!(bench.core.state.r[15], length);
        }
    }

    /// A7.7.258: WFE with an event registered clears it and goes on, and without one waits.
    #[test]
    fn wfe_consumes_an_event_or_waits() {
        for code in [&[0xBF20, 0xBF20][..], &[0xF3AF, 0x8002, 0xF3AF, 0x8002][..]] {
            let (bench, exit) = after(code, 2, |core| core.state.event = 1);
            assert_eq!(exit, Exit::Waiting);
            assert_eq!(bench.core.state.event, 0);
        }
    }

    /// A7.7.127: SEV registers an event on this processor too, which the next WFE consumes.
    #[test]
    fn sev_registers_an_event_the_next_wfe_consumes() {
        assert_eq!(state(&[0xBF40], 1, |_| {}).event, 1);
        assert_eq!(state(&[0xF3AF, 0x8004], 1, |_| {}).event, 1);
        let (bench, exit) = after(&[0xBF40, 0xBF20, 0xBF00], 3, |_| {});
        assert_eq!(exit, Exit::Budget);
        assert_eq!((bench.core.state.event, bench.core.state.sleeping), (0, 0));
    }

    /// Table A5-14: op1 other than 000 is UNDEFINED.
    #[test]
    fn a_32_bit_hint_with_op1_set_is_undefined() {
        for op1 in 1..8 {
            assert!(undefined(&[0xF3AF, 0x8000 | (op1 << 8)]), "op1 {op1}");
        }
    }

    /// A7.7.23: CLREX takes the local monitor back to Open Access, A3.4.
    #[test]
    fn clrex_clears_the_local_monitor() {
        let cleared = state(&[0xF3BF, 0x8F2F], 1, |core| {
            core.state.exclusive_valid = 1;
        });
        assert_eq!(cleared.exclusive_valid, 0);
    }

    /// DSB and DMB change nothing, A7.7.32 and A7.7.33, and ISB ends the block, A7.7.36, with
    /// every option.
    #[test]
    fn the_barriers_change_nothing_and_isb_ends_the_block() {
        let code = [
            0xF3BF, 0x8F4F, 0xF3BF, 0x8F5F, 0xF3BF, 0x8F6F, 0xF3BF, 0x8F43,
        ];
        let mut expected = Bench::new(&[]).core.state.clone();
        expected.r[15] = 16;
        assert_eq!(state(&code, 4, |_| {}), expected);
        assert_eq!(decoded(&[0xF3BF, 0x8F4F], 0), (Ok(()), false));
        assert_eq!(decoded(&[0xF3BF, 0x8F5F], 0), (Ok(()), false));
        assert_eq!(decoded(&[0xF3BF, 0x8F6F], 0), (Ok(()), true));
        assert_eq!(decoded(&[0xF3BF, 0x8F60], 0), (Ok(()), true));
    }

    /// A5.1.1: a bit an encoding diagram marks (0) that's 1, or (1) that's 0, makes the instruction
    /// UNPREDICTABLE, and it runs as if the bit were right. CPS, B5.2.1, MRS, B5.2.2, MSR, B5.2.3,
    /// and CLREX, A7.7.23, each with every such bit flipped.
    #[test]
    fn bits_marked_0_or_1_are_not_checked() {
        const CPSID_I: u16 = 0xB67E;
        const MRS_R0_IPSR: [u16; 2] = [0xF3F0, 0xA005];
        const MSR_PRIMASK_R1: [u16; 2] = [0xF391, 0xAB10];
        const CLREX: [u16; 2] = [0xF3B0, 0xA020];
        const CPSIE_I: u16 = 0xB662;
        let code = [
            CPSID_I,
            MRS_R0_IPSR[0],
            MRS_R0_IPSR[1],
            CLREX[0],
            CLREX[1],
            CPSIE_I,
            MSR_PRIMASK_R1[0],
            MSR_PRIMASK_R1[1],
        ];
        let ran = state(&code, 3, |core| {
            core.state.ipsr = 11;
            core.state.exclusive_valid = 1;
        });
        assert_eq!((ran.primask, ran.r[0], ran.exclusive_valid), (1, 11, 0));
        let ran = state(&code, 5, |core| core.state.r[1] = 1);
        assert_eq!(ran.primask, 1, "cleared by CPSIE and written by MSR");
    }

    /// Table A5-15's other ops are UNDEFINED.
    #[test]
    fn the_unallocated_miscellaneous_control_ops_are_undefined() {
        for op in [0, 1, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15] {
            assert!(undefined(&[0xF3BF, 0x8F0F | (op << 4)]), "op {op:#06b}");
        }
    }

    /// A7.7.12 encoding T3 builds its offset from `S:J2:J1:imm6:imm11:'0'` and branches on its
    /// condition.
    #[test]
    fn b_t3_builds_its_offset_from_s_j2_j1_imm6_imm11() {
        let equal = |core: &mut Family| core.state.z = 1;
        assert_eq!(next(&[0xF000, 0x8080], equal), 0x104);
        assert_eq!(next(&[0xF000, 0x8080], |_| {}), 4);
        assert_eq!(next(&[0xF000, 0xA000], equal), 0x4_0004, "J1 is bit 18");
        assert_eq!(next(&[0xF000, 0x8800], equal), 0x8_0004, "J2 is bit 19");
        assert_eq!(
            next(&[0xF03F, 0x8000], equal),
            0x3_F004,
            "imm6 is bits 17 to 12"
        );
        let mut bench = Bench::new(&[]);
        bench.place(0x10, &[0xF47F, 0xAFFF]);
        bench.core.state.r[15] = 0x10;
        bench.run(1);
        assert_eq!(bench.core.state.r[15], 0x12, "S sign-extends");
    }

    /// A7.7.12 encoding T4 builds its offset from `S:I1:I2:imm10:imm11:'0'`, with each `I` the
    /// inverse of its `J` exclusive-ored with S.
    #[test]
    fn b_t4_builds_its_offset_with_i1_and_i2() {
        assert_eq!(next(&[0xF001, 0xB800], |_| {}), 0x1004);
        assert_eq!(next(&[0xF400, 0x9000], |_| {}), 0xFF00_0004);
        assert_eq!(next(&[0xF000, 0x9800], |_| {}), 0x0080_0004);
        assert_eq!(next(&[0xF000, 0xB000], |_| {}), 0x0040_0004);
        let mut bench = Bench::new(&[0xF7FF, 0xBFFE]);
        assert_eq!(bench.run(5), (Exit::Waiting, 1), "a branch to itself waits");
        assert_eq!(bench.core.state.r[15], CODE);
    }

    /// A7.7.18: BL writes the next instruction's address with bit 0 set to `LR`, and branches as
    /// encoding T4 does.
    #[test]
    fn bl_links_the_next_instruction_and_branches() {
        let called = state(&[0xF001, 0xF800], 1, |_| {});
        assert_eq!((called.r[15], called.r[14]), (0x1004, 5));
        let called = state(&[0xF400, 0xD000], 1, |_| {});
        assert_eq!((called.r[15], called.r[14]), (0xFF00_0004, 5));
    }

    /// BL last in an IT block runs under its condition, `LR` and all.
    #[test]
    fn bl_last_in_an_it_block_runs_under_its_condition() {
        let code = [0xBF18, 0xF001, 0xF800];
        let skipped = state(&code, 2, |core| {
            core.state.z = 1;
            core.state.r[14] = 0xEEEE;
        });
        assert_eq!((skipped.r[15], skipped.r[14]), (6, 0xEEEE));
        let called = state(&code, 2, |_| {});
        assert_eq!((called.r[15], called.r[14]), (0x1006, 7));
    }

    /// Table A5-13's gaps: UDF encoding T2, op1 1x0, op 011110x, and op 1111xxx with op1 0x0.
    #[test]
    fn the_unallocated_branch_and_control_encodings_are_undefined() {
        for code in [
            [0xF7F0, 0xA000],
            [0xF7FF, 0xAFFF],
            [0xF000, 0xC000],
            [0xF000, 0xE000],
            [0xF3C0, 0x8000],
            [0xF3D0, 0x8000],
            [0xF780, 0x8000],
            [0xF7F0, 0x8000],
        ] {
            assert!(undefined(&code), "{code:04x?}");
        }
    }

    /// B5.2.2: each view of `xPSR` reads its own fields, and EPSR reads as zero.
    #[test]
    fn mrs_reads_each_view_of_the_program_status_registers() {
        let mut code = Vec::new();
        for (d, sysm) in [(0, 0), (1, 1), (2, 2), (3, 3), (4, IPSR), (5, 6), (6, 7)] {
            code.extend(mrs(d, sysm));
        }
        let read = state(&code, 7, |core| {
            core.state.set_xpsr(0xA80A_0023 | mask(xpsr::T));
            core.state.r[5] = 0x5555;
        });
        assert_eq!(
            read.r[..7],
            [
                0xA80A_0000,
                0xA80A_0023,
                0xA80A_0000,
                0xA80A_0023,
                0x23,
                0,
                0x23
            ]
        );
    }

    /// Privileged, MRS reads both stack pointers, the masks and `CONTROL` with FPCA.
    #[test]
    fn mrs_reads_the_stack_pointers_and_masks_privileged() {
        let mut code = Vec::new();
        for (d, sysm) in [
            (0, MSP),
            (1, PSP),
            (2, PRIMASK),
            (3, BASEPRI),
            (4, BASEPRI_MAX),
            (5, FAULTMASK),
            (6, CONTROL),
        ] {
            code.extend(mrs(d, sysm));
        }
        let (bench, _) = after(&code, 7, |core| {
            core.state.r[13] = 0x2000_1000;
            core.state.other_sp = 0x2000_2000;
            core.state.primask = 1;
            core.state.faultmask = 1;
            core.state.control = mask(control::FPCA);
            core.scs.write_basepri(0x40);
        });
        assert_eq!(
            bench.core.state.r[..7],
            [0x2000_1000, 0x2000_2000, 1, 0x40, 0x40, 1, 4]
        );
    }

    /// Unprivileged, the stack pointers and the masks read as zero and `CONTROL` still reads.
    #[test]
    fn mrs_reads_zero_for_the_stack_pointers_and_masks_unprivileged() {
        let mut code = Vec::new();
        for (d, sysm) in [
            (0, MSP),
            (1, PSP),
            (2, PRIMASK),
            (3, BASEPRI),
            (4, BASEPRI_MAX),
            (5, FAULTMASK),
            (6, CONTROL),
        ] {
            code.extend(mrs(d, sysm));
        }
        let (bench, _) = after(&code, 7, |core| {
            unprivileged(core);
            core.state.other_sp = 0x2000_2000;
            core.state.primask = 1;
            core.state.faultmask = 1;
            core.scs.write_basepri(0x40);
            core.state.r[..7].fill(0xFFFF);
        });
        assert_eq!(bench.core.state.r[..7], [0, 0, 0, 0, 0, 0, 1]);
    }

    /// MRS of a `SYSm` Table B5-1 doesn't list is UNPREDICTABLE, B5.2.2, and reads zero as the
    /// pseudocode's `R[d] = Zeros(32)` leaves it.
    #[test]
    fn mrs_of_a_register_v7m_lacks_reads_zero() {
        for sysm in [4, 10, 15, 21, 24, 0xFF] {
            let read = state(&mrs(0, sysm), 1, |core| {
                core.state.r[0] = 0xFFFF;
                core.state.set_xpsr(APSR | mask(xpsr::T));
            });
            assert_eq!(read.r[0], 0, "SYSm {sysm}");
        }
    }

    /// MRS to SP is UNPREDICTABLE, B5.2.2, and writes it as `R[13]` does, bits 1 and 0 clear. To
    /// the PC it's UNDEFINED, since `R[]` can't write the PC, B1.4.7.
    #[test]
    fn mrs_to_the_sp_clears_bits_1_and_0_and_to_the_pc_is_undefined() {
        let read = state(&mrs(13, IPSR), 1, |core| core.state.ipsr = 0x23);
        assert_eq!(read.r[13], 0x20);
        assert!(undefined(&mrs(15, 0)));
    }

    /// MRS to SP of the other stack pointer, privileged, makes the stack in use hold it, and
    /// leaves the other alone.
    #[test]
    fn mrs_to_the_sp_of_a_stack_pointer_copies_it_privileged() {
        let read = state(&mrs(13, PSP), 1, |core| core.state.other_sp = 0x2000_2000);
        assert_eq!((read.r[13], read.other_sp), (0x2000_2000, 0x2000_2000));
        let read = state(&mrs(13, MSP), 1, |core| core.state.r[13] = 0x2000_1000);
        assert_eq!(read.r[13], 0x2000_1000);
    }

    /// B5.2.3 with Table B5-2: `mask` picks N, Z, C, V and Q, GE, or both, from any privilege, and
    /// the next instruction sees them.
    #[test]
    fn msr_writes_the_apsr_fields_its_mask_names() {
        let written = |mask: u16, sysm: u16| {
            let [a, b] = msr(0, mask, sysm);
            let [c, d] = mrs(1, 3);
            state(&[a, b, c, d], 2, |core| {
                unprivileged(core);
                core.state.r[0] = u32::MAX;
            })
        };
        assert_eq!(written(0b10, 0).r[1], APSR_NZCVQ);
        assert_eq!(written(0b01, 0).r[1], mask(xpsr::GE));
        assert_eq!(written(0b11, 0).r[1], APSR);
        assert_eq!(written(0b11, 1).r[1], APSR, "IAPSR");
        assert_eq!(written(0b11, 3).r[1], APSR, "XPSR keeps IPSR and EPSR");
        let xpsr = written(0b11, 3);
        assert_eq!((xpsr.ipsr, xpsr.it, xpsr.t), (0, 0, 1));
        assert_eq!(
            written(0b00, 0).r[1],
            0,
            "mask 00 is UNPREDICTABLE and writes nothing"
        );
    }

    /// MSR with a mask other than 10 to a register past the APSR is UNPREDICTABLE, B5.2.3, and
    /// writes it, since the operation reads the mask only for the APSR.
    #[test]
    fn msr_past_the_apsr_writes_whatever_the_mask() {
        for mask in [0b00, 0b01, 0b11] {
            let written = state(&msr(0, mask, PRIMASK), 1, |core| core.state.r[0] = 1);
            assert_eq!(written.primask, 1, "mask {mask:02b}");
            let written = state(&msr(0, mask, PSP), 1, |core| core.state.r[0] = 0x2000_0100);
            assert_eq!(written.other_sp, 0x2000_0100, "mask {mask:02b}");
        }
    }

    /// The processor ignores an MSR to IPSR, EPSR or IEPSR, and to a `SYSm` Table B5-1 doesn't
    /// list, which is UNPREDICTABLE, B5.2.3.
    #[test]
    fn msr_to_ipsr_epsr_and_unlisted_registers_changes_nothing() {
        for (mask, sysm) in [
            (0b10, 5),
            (0b11, 6),
            (0b11, 7),
            (0b10, 4),
            (0b10, 10),
            (0b10, 21),
            (0b10, 0xFF),
        ] {
            let prepare = |core: &mut Family| {
                core.state.ipsr = 11;
                core.state.r[0] = u32::MAX;
            };
            let mut expected = Bench::new(&[]);
            prepare(&mut expected.core);
            expected.core.state.r[15] = 4;
            assert_eq!(
                state(&msr(0, mask, sysm), 1, prepare),
                expected.core.state,
                "SYSm {sysm}"
            );
        }
    }

    /// Privileged, MSR writes the stack pointer it names with bits 1 and 0 clear, B1.4.1.
    /// Unprivileged, it writes neither.
    #[test]
    fn msr_writes_the_stack_pointers_privileged() {
        let [a, b] = msr(0, 0b10, MSP);
        let [c, d] = msr(1, 0b10, PSP);
        let code = [a, b, c, d];
        let values = |core: &mut Family| {
            core.state.r[0] = 0x2000_0103;
            core.state.r[1] = 0x2000_0207;
            core.state.other_sp = 0x2000_3000;
        };
        let written = state(&code, 2, values);
        assert_eq!(
            (written.r[13], written.other_sp),
            (0x2000_0100, 0x2000_0204)
        );
        let ignored = state(&code, 2, |core| {
            values(core);
            unprivileged(core);
        });
        assert_eq!(
            (ignored.r[13], ignored.other_sp),
            (Bench::new(&[]).core.state.r[13], 0x2000_3000)
        );
    }

    /// Privileged, MSR writes `PRIMASK`, `BASEPRI` with its unimplemented bits zero, and
    /// `FAULTMASK`. Unprivileged, it writes none of them.
    #[test]
    fn msr_writes_the_masks_privileged() {
        let mut code = Vec::new();
        for (n, sysm) in [(0, PRIMASK), (1, BASEPRI), (2, FAULTMASK)] {
            code.extend(msr(n, 0b10, sysm));
        }
        let values = |core: &mut Family| {
            core.state.r[0] = 0xFFFF_FFFF;
            core.state.r[1] = 0x45;
            core.state.r[2] = 0xFFFF_FFFF;
        };
        let (bench, _) = after(&code, 3, values);
        let state = &bench.core.state;
        assert_eq!((state.primask, state.faultmask), (1, 1));
        assert_eq!(bench.core.scs.basepri(), 0x40);
        let (bench, _) = after(&code, 3, |core| {
            values(core);
            unprivileged(core);
        });
        let state = &bench.core.state;
        assert_eq!((state.primask, state.faultmask), (0, 0));
        assert_eq!(bench.core.scs.basepri(), 0);
    }

    /// B5.2.3: `BASEPRI_MAX` writes only a nonzero value that raises the priority `BASEPRI` masks,
    /// so a lower one or zero leaves it.
    #[test]
    fn basepri_max_only_raises_the_masked_priority() {
        let mut code = Vec::new();
        for n in 0..4 {
            code.extend(msr(n, 0b10, BASEPRI_MAX));
        }
        let mut bench = Bench::new(&code);
        bench.core.state.r[..4].copy_from_slice(&[0x80, 0xA0, 0x40, 0]);
        for held in [0x80, 0x80, 0x40, 0x40] {
            bench.run(1);
            assert_eq!(bench.core.scs.basepri(), held);
        }
    }

    /// FAULTMASK takes no write while its execution priority is -1 or below: from HardFault, from
    /// NMI, or with it already set.
    #[test]
    fn faultmask_takes_no_write_at_priority_minus_one() {
        let code = msr(0, 0b10, FAULTMASK);
        for number in [NMI, HARD_FAULT] {
            let written = state(&code, 1, |core| {
                handling(core, number);
                core.state.r[0] = 1;
            });
            assert_eq!(written.faultmask, 0);
        }
        let held = state(&code, 1, |core| core.state.faultmask = 1);
        assert_eq!(held.faultmask, 1);
        let svcall = state(&code, 1, |core| {
            core.state.ipsr = 11;
            core.state.r[0] = 1;
        });
        assert_eq!(svcall.faultmask, 1);
    }

    /// B1.5.4's `ExecutionPriority()` counts every active exception, so a HardFault or NMI still
    /// active in Thread mode, which `CCR.NONBASETHRDENA` allows, keeps MSR and CPSID off
    /// `FAULTMASK` though IPSR is 0.
    #[test]
    fn faultmask_takes_no_write_with_hard_fault_or_nmi_active_in_thread_mode() {
        for number in [NMI, HARD_FAULT] {
            let active = |core: &mut Family| {
                handling(core, number);
                core.state.ipsr = 0;
                core.state.r[0] = 1;
            };
            assert_eq!(state(&msr(0, 0b10, FAULTMASK), 1, active).faultmask, 0);
            assert_eq!(state(&[0xB671], 1, active).faultmask, 0);
        }
    }

    /// MSR with `Rn` 13 or 15 is UNPREDICTABLE, B5.2.3, and reads `R[n]` as any other does: the
    /// SP, or the instruction's address plus 4, A2.3.1.
    #[test]
    fn msr_from_the_sp_or_the_pc_writes_what_r_n_reads() {
        let from_sp = state(&msr(13, 0b10, PSP), 1, |_| {});
        assert_eq!(from_sp.other_sp, from_sp.r[13]);
        let mut bench = Bench::new(&[]);
        bench.place(0x100, &msr(15, 0b10, PSP));
        bench.core.state.r[15] = 0x100;
        bench.run(1);
        assert_eq!(bench.core.state.other_sp, 0x104);
        let flags = state(&msr(15, 0b10, 0), 1, |core| core.state.n = 1);
        assert_eq!(
            (flags.n, flags.z, flags.c, flags.v, flags.q),
            (0, 0, 0, 0, 0)
        );
    }

    /// In Thread mode, MSR to `CONTROL` writes nPRIV, SPSEL and FPCA, and SPSEL swaps the stack
    /// `R13` is. Once unprivileged, the processor takes no more writes.
    #[test]
    fn msr_control_switches_the_stack_and_drops_privilege_in_thread_mode() {
        let mut code = Vec::new();
        for n in 0..3 {
            code.extend(msr(n, 0b10, CONTROL));
        }
        let mut bench = Bench::new(&code);
        bench.core.state.r[13] = 0x2000_1000;
        bench.core.state.other_sp = 0x2000_2000;
        bench.core.state.r[..3].copy_from_slice(&[
            mask(control::SPSEL) | mask(control::FPCA),
            mask(control::NPRIV),
            mask(control::SPSEL),
        ]);
        bench.run(1);
        let state = &bench.core.state;
        assert_eq!(state.control, mask(control::SPSEL) | mask(control::FPCA));
        assert_eq!((state.r[13], state.other_sp), (0x2000_2000, 0x2000_1000));
        bench.run(2);
        let state = &bench.core.state;
        assert_eq!(state.control, mask(control::NPRIV));
        assert_eq!((state.r[13], state.other_sp), (0x2000_1000, 0x2000_2000));
    }

    /// Without the DSP extension MRS reads no GE and MSR writes none, B5.2.2 and B5.2.3, and
    /// without the floating-point extension `CONTROL` has no FPCA, B1.4.4.
    #[test]
    fn a_core_without_the_extensions_has_no_ge_and_no_fpca() {
        let mut code = Vec::new();
        code.extend(msr(0, 0b11, 0));
        code.extend(mrs(1, 0));
        code.extend(msr(0, 0b10, CONTROL));
        code.extend(mrs(2, CONTROL));
        let mut bench = Bench::of(&spec_of(Variant::M3, Fpu::None, MpuRegions::Eight), &code);
        bench.core.state.ge = 0b0101;
        bench.core.state.r[0] = u32::MAX;
        assert_eq!(bench.run(4).1, 4);
        let state = &bench.core.state;
        assert_eq!((state.r[1], state.ge), (APSR_NZCVQ, 0b0101));
        assert_eq!(state.r[2], mask(control::NPRIV) | mask(control::SPSEL));
    }

    /// In Handler mode, MSR to `CONTROL` leaves SPSEL, so `R13` stays the main stack.
    #[test]
    fn msr_control_leaves_spsel_in_handler_mode() {
        let written = state(&msr(0, 0b10, CONTROL), 1, |core| {
            core.state.ipsr = 11;
            core.state.r[13] = 0x2000_1000;
            core.state.r[0] = mask(control::NPRIV) | mask(control::SPSEL) | mask(control::FPCA);
        });
        assert_eq!(written.control, mask(control::NPRIV) | mask(control::FPCA));
        assert_eq!(written.r[13], 0x2000_1000);
    }

    /// MSR to the stack pointers, the masks or `CONTROL` ends the block, and to the APSR doesn't.
    #[test]
    fn msr_ends_the_block_after_what_interrupts_and_translation_depend_on() {
        assert_eq!(decoded(&msr(0, 0b10, 0), 0), (Ok(()), false));
        for sysm in [MSP, PSP, PRIMASK, BASEPRI, BASEPRI_MAX, FAULTMASK, CONTROL] {
            assert_eq!(decoded(&msr(0, 0b10, sysm), 0), (Ok(()), true), "{sysm}");
        }
    }
}