vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
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
//! `AArch64` data-processing instructions, run natively from a code page.

use std::cell::Cell;
use std::ffi::c_void;
use std::sync::Once;

use yaxpeax_arch::{Decoder, ReaderBuilder};
use yaxpeax_arm::armv8::a64::{self, Operand};

use super::{
    Findings, branches_on_unknown_flags, condition_differs, float_bits, lifted,
    register_differences, same_float_bits, unsupported, value,
};
use vlk_base::target::Isa;
use vlk_eval::eval::{self, hash};
use vlk_ir::ir::FunctionIr;

/// The general registers a case may use: the harness keeps its state
/// pointer in x28, x18 belongs to the platform, and x29, x30 and sp hold
/// the frame.
fn usable(index: u16) -> bool {
    !matches!(index, 18 | 28 | 29 | 30)
}

/// Saves the callee-saved registers, keeps the state pointer in x28, and
/// loads v0–v7, NZCV and x0–x27 (but x18) from it.
const PROLOGUE: [u32; 27] = [
    0xa9ba_7bfd,
    0xa901_53f3,
    0xa902_5bf5,
    0xa903_63f7,
    0xa904_6bf9,
    0xa905_73fb,
    0xaa00_03fc,
    0xad47_8780,
    0xad48_8f82,
    0xad49_9784,
    0xad4a_9f86,
    0xf940_7380,
    0xd51b_4200,
    0xa940_0780,
    0xa941_0f82,
    0xa942_1784,
    0xa943_1f86,
    0xa944_2788,
    0xa945_2f8a,
    0xa946_378c,
    0xa947_3f8e,
    0xa948_4790,
    0xa949_d393,
    0xa94a_db95,
    0xa94b_e397,
    0xa94c_eb99,
    0xf940_6f9b,
];

/// Stores v0–v7, x0–x27 (but x18) and NZCV back and returns.
const EPILOGUE: [u32; 27] = [
    0xad07_8780,
    0xad08_8f82,
    0xad09_9784,
    0xad0a_9f86,
    0xa900_0780,
    0xa901_0f82,
    0xa902_1784,
    0xa903_1f86,
    0xa904_2788,
    0xa905_2f8a,
    0xa906_378c,
    0xa907_3f8e,
    0xa908_4790,
    0xa909_d393,
    0xa90a_db95,
    0xa90b_e397,
    0xa90c_eb99,
    0xf900_6f9b,
    0xd53b_4200,
    0xf900_7380,
    0xa941_53f3,
    0xa942_5bf5,
    0xa943_63f7,
    0xa944_6bf9,
    0xa945_73fb,
    0xa8c6_7bfd,
    0xd65f_03c0,
];

const RET: u32 = 0xd65f_03c0;
const NZCV: usize = 28;

/// x0–x27 by index, then NZCV, a word of padding, and the halves of v0–v7
/// from word 30, as the prologue and epilogue lay them out.
type State = [u64; 46];

const VECTORS: usize = 30;

fn registers(initial: &State) -> Vec<(u16, u64)> {
    (0..28u16)
        .filter(|index| usable(*index))
        .map(|index| (index, initial[usize::from(index)]))
        .chain((0..16).map(|half| {
            (
                vlk_arch::arch::aarch64::V0 + half as u16,
                initial[VECTORS + half],
            )
        }))
        .collect()
}

unsafe extern "C" {
    fn mmap(
        addr: *mut c_void,
        len: usize,
        prot: i32,
        flags: i32,
        fd: i32,
        offset: i64,
    ) -> *mut c_void;
    fn munmap(addr: *mut c_void, len: usize) -> i32;
    fn pthread_jit_write_protect_np(enabled: i32);
    fn sys_icache_invalidate(start: *mut c_void, len: usize);
    fn sigaction(signal: i32, action: *const SignalAction, old: *mut SignalAction) -> i32;
}

#[repr(C)]
struct SignalAction {
    handler: usize,
    mask: u32,
    flags: i32,
}

const SIGILL: i32 = 4;
const SIGBUS: i32 = 10;
const SIGSEGV: i32 = 11;

thread_local! {
    /// The code page of the case this thread runs now, and whether its
    /// instruction turned out to be one the processor does not define or
    /// an access it faults on.
    static RUNNING: Cell<usize> = const { Cell::new(0) };
    static UNDEFINED: Cell<bool> = const { Cell::new(false) };
}

/// Steps over an undefined instruction or a faulting access in the case's
/// code, so the case ends and reports it; a fault anywhere else stays fatal.
extern "C" fn on_instruction_fault(signal: i32, _: *mut c_void, context: *mut c_void) {
    // The Darwin arm64 layout: the machine context pointer sits 48 bytes
    // into the user context, and its program counter 272 bytes into that.
    // SAFETY: the kernel passes a valid user context to the handler.
    unsafe {
        let machine = *(context.cast::<u8>().add(48).cast::<*mut u8>());
        let pc = machine.add(272).cast::<u64>();
        let base = RUNNING.with(Cell::get) as u64;
        if base != 0 && (base..base + PAGE as u64).contains(&*pc) {
            *pc += 4;
            UNDEFINED.with(|undefined| undefined.set(true));
        } else {
            let default = SignalAction {
                handler: 0,
                mask: 0,
                flags: 0,
            };
            sigaction(signal, &default, std::ptr::null_mut());
        }
    }
}

const PAGE: usize = 1 << 14;

/// A page the thread can write code into and run.
struct Page {
    base: *mut u32,
    len: usize,
}

impl Page {
    fn new() -> Self {
        const PROT_ALL: i32 = 1 | 2 | 4;
        const MAP_PRIVATE_ANON_JIT: i32 = 0x0002 | 0x1000 | 0x0800;
        let len = PAGE;
        static HANDLER: Once = Once::new();
        HANDLER.call_once(|| {
            const SA_SIGINFO: i32 = 0x40;
            let action = SignalAction {
                handler: on_instruction_fault as *const () as usize,
                mask: 0,
                flags: SA_SIGINFO,
            };
            for signal in [SIGILL, SIGBUS, SIGSEGV] {
                // SAFETY: action is valid for this call and the handler touches only
                // the case's state. Installing signal handlers requires the OS API.
                unsafe { sigaction(signal, &action, std::ptr::null_mut()) };
            }
        });
        // SAFETY: an anonymous mapping, checked below.
        let base = unsafe {
            mmap(
                std::ptr::null_mut(),
                len,
                PROT_ALL,
                MAP_PRIVATE_ANON_JIT,
                -1,
                0,
            )
        };
        assert!(base as isize != -1, "mapping a code page");
        Self {
            base: base.cast(),
            len,
        }
    }

    /// Runs `body` between the prologue and epilogue on `state`; false when
    /// the processor does not define one of its instructions.
    fn run(&self, body: &[u32], state: &mut State) -> bool {
        let code: Vec<u32> = PROLOGUE
            .iter()
            .chain(body)
            .chain(&EPILOGUE)
            .copied()
            .collect();
        assert!(code.len() * 4 <= self.len);
        // SAFETY: the page is this thread's to write while write protection
        // is off, and the code saves and restores what the calling
        // convention requires.
        unsafe {
            pthread_jit_write_protect_np(0);
            std::ptr::copy_nonoverlapping(code.as_ptr(), self.base, code.len());
            pthread_jit_write_protect_np(1);
            sys_icache_invalidate(self.base.cast(), code.len() * 4);
            let entry: extern "C" fn(*mut u64) = std::mem::transmute(self.base);
            UNDEFINED.with(|undefined| undefined.set(false));
            RUNNING.with(|running| running.set(self.base as usize));
            entry(state.as_mut_ptr());
            RUNNING.with(|running| running.set(0));
        }
        !UNDEFINED.with(Cell::get)
    }
}

impl Drop for Page {
    fn drop(&mut self) {
        // SAFETY: the mapping made in `new`.
        unsafe { munmap(self.base.cast(), self.len) };
    }
}

fn decode(word: u32) -> Option<a64::Instruction> {
    let bytes = word.to_le_bytes();
    let mut reader = ReaderBuilder::<u64, u8>::read_from(&bytes[..]);
    a64::InstDecoder::default().decode(&mut reader).ok()
}

/// Whether every operand is a usable register, a condition or an immediate;
/// vector registers only from v0 to v7, which the harness loads.
fn register_only(instruction: &a64::Instruction) -> bool {
    instruction.operands.iter().all(|operand| match *operand {
        Operand::Nothing
        | Operand::ConditionCode(_)
        | Operand::Immediate(_)
        | Operand::Imm64(_)
        | Operand::Imm16(_)
        | Operand::ImmediateDouble(_)
        | Operand::ImmShift(..) => true,
        Operand::SIMDRegister(_, number)
        | Operand::SIMDRegisterElements(_, number, _)
        | Operand::SIMDRegisterElementsLane(_, number, ..) => number < 8,
        Operand::Register(_, index) | Operand::RegShift(_, _, _, index) => {
            index == 31 || usable(index)
        }
        Operand::RegisterOrSP(_, index) => index != 31 && usable(index),
        _ => false,
    })
}

/// A random instruction from the data-processing groups, which read and
/// write only registers and flags.
fn instruction(seed: u64) -> Option<(u32, a64::Instruction)> {
    let bits = hash(seed, 1) as u32;
    let word = match hash(seed, 2) % 6 {
        // Advanced SIMD on vectors, and on scalars.
        4 => (bits & !(0b1111 << 25 | 1 << 31)) | (0b0111 << 25),
        5 => (bits & !(0b11 << 30 | 0b1111 << 25)) | (0b01 << 30 | 0b1111 << 25),
        0 => (bits & !(0b111 << 26)) | (0b100 << 26),
        1 => (bits & !(0b111 << 25)) | (0b101 << 25),
        // Scalar floating point: data processing and conversions, and the
        // fused multiply-adds.
        2 => (bits & !(0b1_1111 << 24 | 1 << 30)) | (0b1_1110 << 24),
        _ => (bits & !(0b1_1111 << 24 | 1 << 30)) | (0b1_1111 << 24),
    };
    let decoded = decode(word)?;
    register_only(&decoded).then_some((word, decoded))
}

/// A compare that sets every flag from two usable registers: `cmp`, `cmn`
/// or `tst`, at either width.
fn compare(seed: u64) -> u32 {
    const FORMS: [u32; 6] = [
        0xeb00_001f,
        0x6b00_001f,
        0xab00_001f,
        0x2b00_001f,
        0xea00_001f,
        0x6a00_001f,
    ];
    let register = |key| {
        let index = (hash(seed, key) % 28) as u32;
        if index == 18 { 0 } else { index }
    };
    FORMS[(hash(seed, 3) % 6) as usize] | register(4) << 16 | register(5) << 5
}

/// Whether the condition with encoding `code` holds for `nzcv` as the
/// processor reads it.
fn condition(code: u32, nzcv: u64) -> bool {
    let (n, z, c, v) = (
        nzcv >> 31 & 1 == 1,
        nzcv >> 30 & 1 == 1,
        nzcv >> 29 & 1 == 1,
        nzcv >> 28 & 1 == 1,
    );
    let base = match code >> 1 {
        0 => z,
        1 => c,
        2 => n,
        3 => v,
        4 => c && !z,
        5 => n == v,
        _ => n == v && !z,
    };
    if code & 1 == 1 { !base } else { base }
}

fn lift_words(words: &[u32]) -> Option<FunctionIr> {
    lifted(
        Isa::AArch64,
        words.iter().flat_map(|word| word.to_le_bytes()).collect(),
    )
}

fn check_instruction(page: &Page, seed: u64, findings: &mut Findings) {
    // One random instruction, or two, so that one can read the flags or
    // overwrite the operands of the other.
    let mut instructions = Vec::new();
    for (index, salt) in [0, 0x5eed].into_iter().enumerate() {
        if index == 1 && hash(seed, 7) & 1 == 0 {
            break;
        }
        let Some(instruction) = instruction(seed ^ salt) else {
            return;
        };
        instructions.push(instruction);
    }
    let setter = compare(seed);
    let body: Vec<u32> = std::iter::once(setter)
        .chain(instructions.iter().map(|(word, _)| *word))
        .collect();
    let kind = instructions
        .iter()
        .map(|(_, decoded)| format!("{:?}", decoded.opcode))
        .collect::<Vec<_>>()
        .join(" then ");
    let Some(ir) = lift_words(&[body.as_slice(), &[RET]].concat()) else {
        return;
    };
    let mut state: State = [0; 46];
    for (index, slot) in state.iter_mut().enumerate().take(28) {
        if usable(index as u16) {
            *slot = value(seed, 0x100 + index as u64);
        }
    }
    for half in 0..16 {
        state[VECTORS + half] = float_bits(seed, 0x200 + half as u64);
    }
    state[NZCV] = (hash(seed, 6) & 0xf) << 28;
    let initial = state;
    if !page.run(&body, &mut state) {
        findings.undefined += 1;
        return;
    }
    // Only an instruction the processor defines counts as one to lift.
    if let Some(name) = unsupported(&ir) {
        *findings.unsupported.entry(name).or_default() += 1;
        return;
    }
    findings.tried += 1;

    let registers = registers(&initial);
    let processor = |index: u16| match index.checked_sub(vlk_arch::arch::aarch64::V0) {
        Some(half) => state[VECTORS + usize::from(half)],
        None => state[usize::from(index)],
    };
    let name = |index: u16| match index.checked_sub(vlk_arch::arch::aarch64::V0) {
        Some(half) if half % 2 == 1 => format!("v{}_hi", half / 2),
        Some(half) => format!("d{}", half / 2),
        None => format!("x{index}"),
    };
    let describe = || {
        let inputs: Vec<String> = registers
            .iter()
            .map(|(index, value)| format!("{}={value:#x}", name(*index)))
            .collect();
        let code: Vec<String> = body
            .iter()
            .map(|word| {
                let text = decode(*word).map(|d| d.to_string()).unwrap_or_default();
                format!("{text} ({word:#010x})")
            })
            .collect();
        format!(
            "{}\n  in: {}\n{}",
            code.join(" ; "),
            inputs.join(" "),
            ir.render()
        )
    };
    if let Some(differ) = register_differences(&ir, &registers, processor, name, |index, a, b| {
        if index >= vlk_arch::arch::aarch64::V0 {
            same_float_bits(a, b)
        } else {
            a == b
        }
    }) {
        Findings::note(&mut findings.registers, kind, || {
            format!("{}\n  {differ}", describe())
        });
        return;
    }

    // b.<cond> +12; mov x0, #0; ret; mov x0, #1; ret
    let setter_kind = decode(setter).map_or(String::new(), |d| format!("{:?}", d.opcode));
    for code in 0..14 {
        let tail = [0x5400_0060 | code, 0xd280_0000, RET, 0xd280_0020, RET];
        let Some(ir) = lift_words(&[body.as_slice(), &tail].concat()) else {
            continue;
        };
        // Flags the lifter does not know are left to the branch.
        if branches_on_unknown_flags(&ir) {
            continue;
        }
        let expected = condition(code, state[NZCV]);
        if let Some(differ) = condition_differs(&ir, &registers, expected) {
            Findings::note(
                &mut findings.conditions,
                format!("{setter_kind} then {kind}, condition {code}"),
                || {
                    format!(
                        "{}\n  condition {code}: {differ}\n{}",
                        describe(),
                        ir.render()
                    )
                },
            );
        }
    }
}

#[test]
fn lifted_instructions_match_the_processor() {
    let page = Page::new();
    let mut findings = Findings::default();
    for seed in 0..200_000 {
        check_instruction(&page, seed, &mut findings);
    }
    findings.assert_agreement();
}

#[test]
fn sqdmulh_vector_results_match_the_processor() {
    struct RestoreFpsr(u64);
    impl Drop for RestoreFpsr {
        fn drop(&mut self) {
            // SAFETY: restores only this thread's saved floating-point status.
            unsafe {
                std::arch::asm!("msr fpsr, {}", in(reg) self.0, options(nomem, nostack, preserves_flags))
            };
        }
    }
    let saved: u64;
    // SAFETY: reads this thread's status without changing it.
    unsafe {
        std::arch::asm!("mrs {}, fpsr", out(reg) saved, options(nomem, nostack, preserves_flags))
    };
    let _restore = RestoreFpsr(saved);
    let page = Page::new();
    let mut checked = 0;
    for (bits, full, base) in [
        (16u32, false, 0x0e60_b400),
        (16, true, 0x4e60_b400),
        (32, false, 0x0ea0_b400),
        (32, true, 0x4ea0_b400),
    ] {
        let limit = 1i64 << (bits - 1);
        let edges = [
            -limit,
            -limit + 1,
            -limit / 2,
            -1,
            0,
            1,
            limit / 2,
            limit - 2,
            limit - 1,
        ];
        for (d, n, m) in [
            (0u16, 1u16, 2u16),
            (1, 1, 2),
            (2, 1, 2),
            (0, 1, 1),
            (1, 1, 1),
        ] {
            let word = base | u32::from(m) << 16 | u32::from(n) << 5 | u32::from(d);
            let decoded = decode(word).expect("valid SQDMULH encoding");
            assert_eq!(decoded.opcode, a64::Opcode::SQDMULH);
            let ir = lift_words(&[word, RET]).expect("SQDMULH lift");
            assert!(unsupported(&ir).is_none(), "{}", ir.render());
            for row in 0..if n == m { 9 } else { 81 } {
                let mut state: State = std::array::from_fn(|index| hash(0x5eed, index as u64));
                state[NZCV] = (checked as u64 & 0xf) << 28;
                let mut fill = |number: u16, second: bool| {
                    for half in 0..if full { 2 } else { 1 } {
                        let mut value = 0;
                        for lane in 0..64 / bits as usize {
                            let position = half * (64 / bits as usize) + lane;
                            let index = if second {
                                row / 9 + 3 * position
                            } else {
                                row % 9 + position
                            };
                            let element = edges[index % edges.len()] as u64 & ((1u64 << bits) - 1);
                            value |= element << (lane * bits as usize);
                        }
                        state[VECTORS + 2 * usize::from(number) + half] = value;
                    }
                };
                fill(n, false);
                if n != m {
                    fill(m, true);
                }
                let initial = state;
                assert!(
                    page.run(&[word], &mut state),
                    "processor rejected {decoded} ({word:#010x})"
                );
                assert_eq!(state[NZCV], initial[NZCV], "{decoded}, row {row}: NZCV");
                let registers = registers(&initial);
                let setup = super::setup(&registers);
                let (after, memory) =
                    eval::state_after(&ir, &setup).expect("modeled SQDMULH result");
                assert!(memory.is_empty());
                for &(index, start) in &registers {
                    let actual = match index.checked_sub(vlk_arch::arch::aarch64::V0) {
                        Some(half) => state[VECTORS + usize::from(half)],
                        None => state[usize::from(index)],
                    };
                    assert_eq!(
                        after.get(&index).copied().unwrap_or(start),
                        actual,
                        "{decoded} ({word:#010x}), row {row}, register {index}"
                    );
                }
                checked += 1;
            }
        }
    }
    assert_eq!(checked, 1044);
    eprintln!("{checked} SQDMULH vector result cases agree; FPSR.QC is outside the IR comparison");
}

/// The pointer registers memory cases address through; they point into the
/// middle of the buffer, and every other register holds a small value.
const POINTERS: [u16; 4] = [1, 2, 3, 4];
const BUFFER: usize = 8192;

/// Whether a load or store addresses only through a pointer register, by
/// an offset that stays within the buffer, and is not one whose result the
/// architecture leaves unpredictable (a written-back base that is also
/// loaded or stored).
fn buffer_access(instruction: &a64::Instruction) -> bool {
    use a64::Opcode as O;
    let plain = matches!(
        instruction.opcode,
        O::LDR
            | O::LDRB
            | O::LDRH
            | O::LDRSB
            | O::LDRSH
            | O::LDRSW
            | O::STR
            | O::STRB
            | O::STRH
            | O::LDUR
            | O::LDURB
            | O::LDURH
            | O::LDURSB
            | O::LDURSH
            | O::LDURSW
            | O::STUR
            | O::STURB
            | O::STURH
            | O::LDP
            | O::STP
            | O::LDPSW
            | O::LDNP
            | O::STNP
            | O::LD1
            | O::LD2
            | O::LD3
            | O::LD4
            | O::ST1
            | O::ST2
            | O::ST3
            | O::ST4
            | O::LD1R
            | O::LD2R
            | O::LD3R
            | O::LD4R
    );
    let mut base = None;
    let mut writeback = false;
    let mut data_registers = Vec::new();
    let operands_fit = instruction.operands.iter().all(|operand| match *operand {
        Operand::Nothing => true,
        Operand::Register(_, index) | Operand::RegisterOrSP(_, index) => {
            data_registers.push(index);
            index == 31 || usable(index) && !POINTERS.contains(&index)
        }
        Operand::SIMDRegister(_, number) => number < 8,
        Operand::SIMDRegisterGroup(_, number, _, count)
        | Operand::SIMDRegisterGroupLane(number, _, count, _) => number + u16::from(count) <= 8,
        Operand::RegPreIndex(reg, offset, back) => {
            base = Some(reg);
            writeback = back;
            offset.unsigned_abs() <= 2048
        }
        Operand::RegPostIndex(reg, offset) => {
            base = Some(reg);
            writeback = true;
            offset.unsigned_abs() <= 2048
        }
        Operand::RegPostIndexReg(reg, index) => {
            base = Some(reg);
            writeback = true;
            usable(index) && !POINTERS.contains(&index) && index != 31
        }
        Operand::RegRegOffset(reg, index, ..) => {
            base = Some(reg);
            usable(index) && !POINTERS.contains(&index) && index != 31
        }
        _ => false,
    });
    let pair_loads_one = matches!(instruction.opcode, O::LDP | O::LDPSW | O::LDNP)
        && data_registers.len() == 2
        && data_registers[0] == data_registers[1];
    plain
        && operands_fit
        && !pair_loads_one
        && base.is_some_and(|base| POINTERS.contains(&base))
        && !(writeback && base.is_some_and(|base| data_registers.contains(&base)))
}

fn memory_instruction(seed: u64) -> Option<(u32, a64::Instruction)> {
    let structures = [
        0x4cdf_a140u32,
        0x4dcb_8540,
        0x4d9f_8540,
        0x4cdf_0d40,
        0x4dff_e940,
        0x0d40_c140,
    ];
    if let Some(word) = structures.get(seed as usize) {
        let word = (word & !(31 << 5)) | (u32::from(POINTERS[0]) << 5);
        let Some(decoded) = decode(word) else {
            return None;
        };
        return buffer_access(&decoded).then_some((word, decoded));
    }
    // Loads and stores: bit 27 set and bit 25 clear, with a pointer register
    // as the base every form names in bits 5 to 9.
    let base = POINTERS[(hash(seed, 2) % 4) as usize] as u32;
    let word = ((hash(seed, 1) as u32 | 1 << 27) & !(1 << 25) & !(0x1f << 5)) | base << 5;
    let decoded = decode(word)?;
    buffer_access(&decoded).then_some((word, decoded))
}

#[test]
fn lifted_memory_accesses_match_the_processor() {
    let page = Page::new();
    let mut findings = Findings::default();
    let mut buffer = vec![0u8; BUFFER];
    let middle = buffer.as_ptr() as u64 + (BUFFER / 2) as u64;
    for seed in 0..60_000u64 {
        let Some((word, decoded)) = memory_instruction(seed) else {
            continue;
        };
        let Some(ir) = lift_words(&[word, RET]) else {
            continue;
        };
        if let Some(name) = unsupported(&ir) {
            *findings.unsupported.entry(name).or_default() += 1;
            continue;
        }
        let mut state: State = [0; 46];
        for (index, slot) in state.iter_mut().enumerate().take(28) {
            if POINTERS.contains(&(index as u16)) {
                *slot = middle + hash(seed, 0x300 + index as u64) % 256;
            } else if usable(index as u16) {
                *slot = hash(seed, 0x100 + index as u64) % 64;
            }
        }
        for half in 0..16 {
            state[VECTORS + half] = float_bits(seed, 0x200 + half as u64);
        }
        for (index, byte) in buffer.iter_mut().enumerate() {
            *byte = hash(seed, 0x400 + index as u64) as u8;
        }
        let initial = state;
        let before = buffer.clone();
        if !page.run(&[word], &mut state) {
            findings.undefined += 1;
            continue;
        }
        findings.tried += 1;
        let registers = registers(&initial);
        let words: Vec<(u64, u64)> = before
            .chunks(8)
            .enumerate()
            .map(|(index, chunk)| {
                (
                    buffer.as_ptr() as u64 + index as u64 * 8,
                    u64::from_le_bytes(chunk.try_into().expect("8 bytes")),
                )
            })
            .collect();
        let setup = eval::Setup {
            seed: 0,
            convention: eval::Convention {
                arguments: &[],
                clobbered: &[],
            },
            registers: &registers,
            memory: &words,
            step_limit: 100,
        };
        let kind = format!("{:?}", decoded.opcode);
        let describe = || format!("{decoded} ({word:#010x})\n{}", ir.render());
        let (after, memory) = match eval::state_after(&ir, &setup) {
            Ok(state) => state,
            Err(reason) => {
                Findings::note(&mut findings.registers, kind, || {
                    format!("{}\n  {reason}", describe())
                });
                continue;
            }
        };
        let processor = |index: u16| match index.checked_sub(vlk_arch::arch::aarch64::V0) {
            Some(half) => state[VECTORS + usize::from(half)],
            None => state[usize::from(index)],
        };
        let mut differ: Vec<String> = registers
            .iter()
            .filter_map(|(index, start)| {
                let lifted = after.get(index).copied().unwrap_or(*start);
                (lifted != processor(*index)).then(|| {
                    format!(
                        "register {index}: lifted {lifted:#x}, processor {:#x}",
                        processor(*index)
                    )
                })
            })
            .collect();
        for (offset, real) in buffer.iter().enumerate() {
            let address = buffer.as_ptr() as u64 + offset as u64;
            let lifted = memory.get(&address).copied().unwrap_or(before[offset]);
            if lifted != *real {
                differ.push(format!(
                    "byte {offset:#x}: lifted {lifted:#x}, processor {real:#x}"
                ));
            }
        }
        if !differ.is_empty() {
            Findings::note(&mut findings.registers, kind, || {
                format!("{}\n  {}", describe(), differ.join("\n  "))
            });
        }
    }
    findings.assert_agreement();
}

#[test]
fn scalar_half_immediate_processor_probe() {
    let page = Page::new();
    let mut state: State = [u64::MAX; 46];
    state[NZCV] = 0;
    assert!(
        page.run(&[0x1eee_1000], &mut state),
        "scalar half immediate did not execute; processor support or FP access is unavailable"
    );
    assert_eq!(state[VECTORS], 0x3c00);
    assert_eq!(state[VECTORS + 1], 0);
    assert_eq!(state[NZCV], 0);
}

#[test]
fn scalar_half_immediates_match_the_processor_without_status_changes() {
    struct RestoreEnvironment {
        control: u64,
        status: u64,
    }
    impl Drop for RestoreEnvironment {
        fn drop(&mut self) {
            // SAFETY: restores this thread's original floating-point environment.
            unsafe {
                std::arch::asm!("msr fpcr, {control}", "msr fpsr, {status}",
                    control = in(reg) self.control, status = in(reg) self.status,
                    options(nomem, nostack, preserves_flags));
            }
        }
    }
    let control: u64;
    let status: u64;
    // SAFETY: reads only this thread's floating-point environment.
    unsafe {
        std::arch::asm!("mrs {control}, fpcr", "mrs {status}, fpsr",
            control = out(reg) control, status = out(reg) status,
            options(nomem, nostack, preserves_flags));
    }
    let _restore = RestoreEnvironment { control, status };
    let modes = [
        0,
        1 << 22,
        2 << 22,
        3 << 22,
        1 << 25,
        1 << 19,
        1 << 24,
        1 << 26,
    ];
    let mode_mask = (3 << 22) | (1 << 25) | (1 << 19) | (1 << 24) | (1 << 26);
    let page = Page::new();
    let mut checked = 0;
    let mut observed_modes = std::collections::BTreeSet::new();
    for (profile, mode) in modes.into_iter().enumerate() {
        let requested = (control & !mode_mask) | mode;
        let actual_control: u64;
        let requested_status =
            (status & !0x0800_009f) | if profile % 2 == 0 { 0x0800_009f } else { 0 };
        // SAFETY: changes only documented mode/status bits, restored on drop.
        unsafe {
            std::arch::asm!("msr fpcr, {requested}", "msr fpsr, {status}", "mrs {actual}, fpcr",
                requested = in(reg) requested, status = in(reg) requested_status,
                actual = out(reg) actual_control,
                options(nomem, nostack, preserves_flags));
        }
        observed_modes.insert(actual_control & mode_mask);
        for immediate in 0u32..256 {
            let bit = u64::from(immediate >> 6 & 1);
            let expected = u64::from(immediate >> 7) << 15
                | (bit ^ 1) << 14
                | (bit * 3) << 12
                | u64::from(immediate & 63) << 6;
            for destination in 0u16..8 {
                let word = 0x1ee0_1000 | immediate << 13 | u32::from(destination);
                let ir = lift_words(&[word, RET]).expect("a scalar half immediate move");
                assert!(unsupported(&ir).is_none(), "{}", ir.render());
                let mut state: State = std::array::from_fn(|index| hash(0x5eed, index as u64));
                state[NZCV] = (checked as u64 & 15) << 28;
                let initial = state;
                let before_status: u64;
                // SAFETY: reads this thread's status immediately before execution.
                unsafe {
                    std::arch::asm!("mrs {}, fpsr", out(reg) before_status,
                        options(nomem, nostack, preserves_flags));
                }
                assert!(
                    page.run(&[word], &mut state),
                    "processor rejected {word:#010x}, FPCR={actual_control:#x}"
                );
                let after_status: u64;
                let after_control: u64;
                // SAFETY: reads this thread's environment after execution.
                unsafe {
                    std::arch::asm!("mrs {status}, fpsr", "mrs {control}, fpcr",
                        status = out(reg) after_status, control = out(reg) after_control,
                        options(nomem, nostack, preserves_flags));
                }
                assert_eq!(after_status, before_status, "{word:#010x}: FPSR");
                assert_eq!(after_control, actual_control, "{word:#010x}: FPCR");
                assert_eq!(state[NZCV], initial[NZCV], "{word:#010x}: NZCV");
                let registers = registers(&initial);
                let setup = super::setup(&registers);
                let (after, memory) = eval::state_after(&ir, &setup).expect("a complete move");
                assert!(memory.is_empty());
                for &(index, start) in &registers {
                    let processor = match index.checked_sub(vlk_arch::arch::aarch64::V0) {
                        Some(half) => state[VECTORS + usize::from(half)],
                        None => state[usize::from(index)],
                    };
                    let wanted = if index == vlk_arch::arch::aarch64::V0 + 2 * destination {
                        expected
                    } else if index == vlk_arch::arch::aarch64::V0 + 2 * destination + 1 {
                        0
                    } else {
                        start
                    };
                    assert_eq!(
                        processor, wanted,
                        "{word:#010x}, FPCR={actual_control:#x}, register {index}: processor"
                    );
                    assert_eq!(
                        after.get(&index).copied().unwrap_or(start),
                        processor,
                        "{word:#010x}, FPCR={actual_control:#x}, register {index}: IR"
                    );
                }
                checked += 1;
            }
        }
    }
    assert_eq!(checked, 16384);
    assert!(
        observed_modes
            .iter()
            .filter(|mode| **mode & !(3 << 22) == 0)
            .count()
            >= 4
    );
    eprintln!(
        "{checked} exact scalar half immediate cases; observed FPCR mode bits {observed_modes:x?}"
    );
}

#[test]
fn table_shift_and_aes_results_match_the_processor() {
    let page = Page::new();
    for word in [
        0x6ee2_4420,
        0x6e22_4420,
        0x4e00_2000,
        0x0e00_7020,
        0x4e28_4820,
        0x4e28_6800,
    ] {
        let ir = lift_words(&[word, RET]).expect("SIMD lift");
        assert!(unsupported(&ir).is_none(), "{}", ir.render());
        for seed in 0..256 {
            let mut state = [0; 46];
            for half in 0..16 {
                state[VECTORS + half] = match seed {
                    0 => 0,
                    1 => u64::MAX,
                    2 => 0x807f_403f_201f_100f,
                    _ => hash(seed, half as u64),
                };
            }
            let registers: Vec<_> = (0..16)
                .map(|half| {
                    (
                        vlk_arch::arch::aarch64::V0 + half as u16,
                        state[VECTORS + half],
                    )
                })
                .collect();
            assert!(page.run(&[word], &mut state), "{word:08x}");
            let (after, _) =
                eval::state_after(&ir, &super::setup(&registers)).expect("SIMD evaluation");
            for (index, initial) in registers {
                assert_eq!(
                    after.get(&index).copied().unwrap_or(initial),
                    state[VECTORS + usize::from(index - vlk_arch::arch::aarch64::V0)],
                    "{word:08x}, seed {seed}, register {index}"
                );
            }
        }
    }
}

#[test]
fn literal_loads_match_the_processor() {
    let page = Page::new();
    for (word, expected) in [
        (0x1800_0040, 0xd503_201fu64),
        (0x5800_0040, 0xd503_201f_d503_201f),
        (0x9800_0040, 0xffff_ffff_d503_201f),
    ] {
        let body = [word, 0x1400_0003, 0xd503_201f, 0xd503_201f];
        let ir = lift_words(&[body.as_slice(), &[RET]].concat()).expect("literal load lift");
        assert!(unsupported(&ir).is_none(), "{}", ir.render());
        let mut state = [0; 46];
        assert!(page.run(&body, &mut state));
        assert_eq!(state[0], expected);
        let memory = [(8, 0xd503_201f_d503_201f)];
        let setup = eval::Setup {
            memory: &memory,
            ..super::setup(&[])
        };
        let (after, _) = eval::state_after(&ir, &setup).expect("literal load evaluation");
        assert_eq!(after.get(&0), Some(&expected));
    }
}