cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
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
//! Differential test of the symbolic Thumb executor against an independent concrete
//! interpreter (`tests/support/armsim.rs`).
//!
//! Each case is one instruction (or a short IT block) placed in a code segment, run from a
//! random register / flag / memory state by both engines.  The terms the symbolic executor
//! produces are evaluated on that state and must agree with the interpreter on every register,
//! every flag (made observable by a trailing sequence of conditional moves), every memory
//! write and the path of executed instructions.

#[path = "support/armsim.rs"]
mod armsim;

use armsim::{Bus, Cpu, SparseMem};
use cverif::image::{Image, Segment};
use cverif::sym::{Ctx, Limits, Mem, Stop, UNINIT_EPOCH};
use cverif::term::{Env, Node, T};
use cverif::thumb::exec::{Callee, Exit, Machine};
use std::collections::{BTreeMap, HashMap};

const CODE: u32 = 0x0001_0000;
const CODE_LEN: usize = 0x800;
const AT: u32 = CODE + 0x400;
const RET: u32 = 0xf000_0001;
const SP: u32 = 0x2000_8000;

struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }

    fn below(&mut self, n: u64) -> u64 {
        self.next() % n
    }

    /// A register value biased towards the cases instruction semantics distinguish.
    fn value(&mut self) -> u32 {
        match self.below(12) {
            0 => 0,
            1 => 1,
            2 => 0xffff_ffff,
            3 => 0x8000_0000,
            4 => 0x7fff_ffff,
            5 => self.below(40) as u32,
            6 => (self.below(64) as u32).wrapping_neg(),
            7 => 1 << self.below(32),
            8 => 0x2000_0000 + (self.below(0x1000) as u32) * 4,
            9 => self.next() as u32 & 0xffff,
            _ => self.next() as u32,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
    /// Registers are constants.
    Concrete,
    /// Registers are symbols pinned by the path condition.
    Pinned,
    /// Like `Pinned`, with the stack pointer a private base as during verification.
    PrivateStack,
}

#[derive(Clone)]
struct State {
    r: [u32; 15],
    flags: [bool; 4], // n z c v
    seed: u64,
}

fn random_state(rng: &mut Rng) -> State {
    let mut r = [0u32; 15];
    for x in r.iter_mut() {
        *x = rng.value();
    }
    r[13] = SP;
    r[14] = RET;
    let f = rng.next();
    State {
        r,
        flags: [f & 1 != 0, f & 2 != 0, f & 4 != 0, f & 8 != 0],
        seed: rng.next(),
    }
}

fn image_for(code: &[u8]) -> Image {
    // Everything around the code under test returns to the caller.
    let mut data = Vec::with_capacity(CODE_LEN);
    while data.len() < CODE_LEN {
        data.extend_from_slice(&0x4770u16.to_le_bytes());
    }
    let o = (AT - CODE) as usize;
    data[o..o + code.len()].copy_from_slice(code);
    Image {
        segments: vec![Segment {
            name: ".text".into(),
            addr: CODE,
            data,
            writable: false,
            exec: true,
            load_addr: None,
        }],
        ..Default::default()
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
enum End {
    Return,
    /// Control left the code segment (a call or jump to somewhere else).
    Left,
    Trap,
    /// Stopped before a system instruction (BKPT, SVC, CPS, WFI, MRS, ...), which both
    /// engines report by name.
    Event(String),
}

#[derive(Debug)]
struct Outcome {
    end: End,
    r: [u32; 15],
    trace: Vec<u32>,
    mem: BTreeMap<u32, u8>,
}

/// Reference run.  `Err` means the reference does not model the case.
fn run_reference(image: &Image, st: &State) -> Result<(Outcome, HashMap<u32, u8>), String> {
    let mut mem = SparseMem::new(st.seed);
    mem.image.push((CODE, image.segments[0].data.clone()));
    let mut cpu = Cpu::new();
    cpu.r[..15].copy_from_slice(&st.r);
    (cpu.n, cpu.z, cpu.c, cpu.v) = (st.flags[0], st.flags[1], st.flags[2], st.flags[3]);
    cpu.pc = AT;
    let mut trace = Vec::new();
    let end = loop {
        if cpu.pc == RET & !1 {
            break End::Return;
        }
        if cpu.pc < CODE || cpu.pc >= CODE + CODE_LEN as u32 {
            break End::Left;
        }
        if trace.len() > 64 {
            return Err("loop".into());
        }
        trace.push(cpu.pc);
        match cpu.step(&mut mem) {
            Ok(()) => {}
            Err(armsim::Stop::Udf) => break End::Trap,
            Err(armsim::Stop::Event(name)) => break End::Event(name),
            Err(e) => return Err(format!("{e:?}")),
        }
    };
    // Self-modifying code is outside what either engine models.
    if mem.written.keys().any(|a| (CODE..CODE + CODE_LEN as u32).contains(a)) {
        return Err("writes code".into());
    }
    let mut r = [0u32; 15];
    r.copy_from_slice(&cpu.r[..15]);
    Ok((
        Outcome {
            end,
            r,
            trace,
            mem: mem.written.into_iter().collect(),
        },
        mem.initial_reads,
    ))
}

fn sym_id(ctx: &Ctx, t: T) -> u32 {
    match ctx.tm.node(t) {
        Node::Sym(id) => *id,
        n => panic!("not a symbol: {n:?}"),
    }
}

/// Symbolic run evaluated on the state.  `Err` means the executor declined the case.
fn run_symbolic(image: &Image, st: &State, mode: Mode, reads: &HashMap<u32, u8>) -> Result<Outcome, String> {
    let mut ctx = Ctx::new(Limits::default());
    let mut env = Env {
        syms: HashMap::new(),
        mem: HashMap::new(),
    };
    for (&a, &b) in reads {
        env.mem.insert((0, a as u64), b);
        env.mem.insert((UNINIT_EPOCH, a as u64), b);
    }
    let mut regs = [0 as T; 16];
    for i in 0..15 {
        let k = ctx.tm.konst(32, st.r[i] as u64);
        regs[i] = match mode {
            Mode::Concrete => k,
            _ if i == 14 => k,
            Mode::PrivateStack if i == 13 => {
                let s = ctx.private_base("SP0");
                env.syms.insert(sym_id(&ctx, s), st.r[i] as u64);
                let low = ctx.tm.extract(s, 0, 3);
                let zero = ctx.tm.konst(3, 0);
                let aligned = ctx.tm.eq(low, zero);
                ctx.pc.push(aligned);
                s
            }
            _ => {
                let s = ctx.named_sym(&format!("r{i}"), 32);
                env.syms.insert(sym_id(&ctx, s), st.r[i] as u64);
                let e = ctx.tm.eq(s, k);
                ctx.pc.push(e);
                s
            }
        };
    }
    regs[15] = ctx.tm.konst(32, 0);
    // The initial contents of every byte the reference read are facts of the path.
    for (&a, &b) in reads {
        let k = ctx.tm.konst(8, b as u64);
        let addr = ctx.tm.konst(32, a as u64);
        let l = ctx.tm.load(0, addr, 1);
        let e = ctx.tm.eq(l, k);
        ctx.pc.push(e);
        if mode == Mode::PrivateStack && a.wrapping_sub(SP).wrapping_add(0x1000) < 0x2000 {
            let addr = ctx.tm.add_const(regs[13], a.wrapping_sub(SP) as i32 as i64 as u64);
            let l = ctx.tm.load(UNINIT_EPOCH, addr, 1);
            let e = ctx.tm.eq(l, k);
            ctx.pc.push(e);
        }
    }
    let lr0 = regs[14];
    let mut m = Machine::new(&mut ctx, AT, regs);
    for (name, v) in ["flag.n", "flag.z", "flag.c", "flag.v"].iter().zip(st.flags) {
        let s = ctx.named_sym(name, 1);
        env.syms.insert(sym_id(&ctx, s), v as u64);
        let k = ctx.tm.konst(1, v as u64);
        let e = ctx.tm.eq(s, k);
        ctx.pc.push(e);
    }
    let classify = |addr: u32| {
        if (CODE..CODE + CODE_LEN as u32).contains(&addr) {
            Callee::Internal
        } else {
            Callee::External("elsewhere".into())
        }
    };
    let end = match m.run(&mut ctx, image, lr0, &classify) {
        Ok(Exit::Return) => End::Return,
        Ok(Exit::Call { .. }) => End::Left,
        Ok(Exit::Trap) => End::Trap,
        Ok(Exit::Asm { name, .. }) => End::Event(name),
        Ok(Exit::Cut(_)) => return Err("loop cut point".into()),
        // A branch to itself: the reference would run until its step budget is gone.
        Ok(Exit::Hang) => return Err("endless loop".into()),
        Err(Stop::Unsupported(s)) => {
            let s = s.split(" at ").next().unwrap_or("");
            return Err(format!("unsupported: {}", s.split(" 0x").next().unwrap_or("")));
        }
        Err(e) => return Err(format!("{e:?}")),
    };
    if !ctx.decisions.is_empty() {
        // The state did not determine a branch: the comparison would follow an arbitrary path.
        return Err("forked".into());
    }
    let mut memo = HashMap::new();
    let mut r = [0u32; 15];
    for i in 0..15 {
        r[i] = ctx.tm.eval(m.regs[i], &env, &mut memo) as u32;
    }
    let mut mem = BTreeMap::new();
    let Mem { world, private, .. } = &m.mem;
    for log in std::iter::once(world).chain(private.values()) {
        for w in log {
            let a = ctx.tm.eval(w.addr, &env, &mut memo) as u32;
            let v = ctx.tm.eval(w.val, &env, &mut memo);
            for i in 0..w.size as u32 {
                mem.insert(a.wrapping_add(i), (v >> (8 * i)) as u8);
            }
        }
    }
    Ok(Outcome {
        end,
        r,
        trace: m.covered.iter().map(|c| c.0).collect(),
        mem,
    })
}

/// `ite <c>; mov<c> rX, #1; mov<!c> rX, #0` for Z, C, N, V into r8..r11.
fn flag_probe() -> Vec<u8> {
    let mut v = Vec::new();
    for (i, cond) in [0u16, 2, 4, 6].into_iter().enumerate() {
        let rd = 8 + i as u16;
        for hw in [0xbf0c | cond << 4, 0xf04f, rd << 8 | 1, 0xf04f, rd << 8] {
            v.extend_from_slice(&hw.to_le_bytes());
        }
    }
    v
}

#[derive(Default)]
struct Stats {
    cases: usize,
    compared: usize,
    declined: BTreeMap<String, usize>,
    gaps: BTreeMap<String, usize>,
    failures: Vec<String>,
}

fn disasm_hint(code: &[u8]) -> String {
    code.chunks(2)
        .map(|c| format!("{:04x}", u16::from_le_bytes([c[0], c[1]])))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Compare both engines on `code` (the instruction(s) under test, followed by whatever the
/// caller appended) from `st`.
fn compare(code: &[u8], st: &State, mode: Mode, stats: &mut Stats) {
    stats.cases += 1;
    let image = image_for(code);
    let (want, reads) = match run_reference(&image, st) {
        Ok(x) => x,
        Err(why) => {
            // Which encodings does the executor accept that the reference does not model?
            // An encoding the architecture leaves unpredictable, or one the reference does not
            // know, must be refused: a core may do anything on it.
            let strict = why.starts_with("Un");
            if (strict || std::env::var_os("CVERIF_DIFF_GAPS").is_some())
                && run_symbolic(&image, st, mode, &HashMap::new()).is_ok()
            {
                let hw1 = u16::from_le_bytes([code[0], code[1]]);
                let class = if is_wide(hw1) {
                    format!("{:03x}x", hw1 >> 4)
                } else {
                    format!("{:02x}xx", hw1 >> 8)
                };
                let kind = why.split('(').next().unwrap_or("").to_string();
                let class = if kind.starts_with("Un") {
                    disasm_hint(&code[..if is_wide(hw1) { 4 } else { 2 }])
                } else {
                    class
                };
                if strict {
                    stats.failures.push(format!("executor accepts {kind} encoding {class}"));
                }
                *stats.gaps.entry(format!("{kind} {class}")).or_default() += 1;
            }
            return;
        }
    };
    let got = match run_symbolic(&image, st, mode, &reads) {
        Ok(x) => x,
        Err(why) => {
            *stats.declined.entry(why).or_default() += 1;
            return;
        }
    };
    stats.compared += 1;
    let mut diff = Vec::new();
    if want.end != got.end {
        diff.push(format!("end: reference {:?}, executor {:?}", want.end, got.end));
    }
    if want.trace != got.trace {
        diff.push(format!("path: reference {:x?}, executor {:x?}", want.trace, got.trace));
    }
    for i in 0..15 {
        // After control leaves through a call the callee-clobbered state is not compared.
        if want.r[i] != got.r[i] {
            diff.push(format!("r{i}: reference {:#x}, executor {:#x}", want.r[i], got.r[i]));
        }
    }
    if want.mem != got.mem {
        let keys: std::collections::BTreeSet<u32> = want.mem.keys().chain(got.mem.keys()).copied().collect();
        for a in keys.into_iter().filter(|a| want.mem.get(a) != got.mem.get(a)).take(4) {
            diff.push(format!(
                "mem[{a:#x}]: reference {:x?}, executor {:x?}",
                want.mem.get(&a),
                got.mem.get(&a)
            ));
        }
    }
    if !diff.is_empty() && stats.failures.len() < 40 {
        stats.failures.push(format!(
            "{} ({mode:?})\n    regs {:x?} nzcv {:?} seed {:#x}\n    {}",
            disasm_hint(code),
            st.r,
            st.flags,
            st.seed,
            diff.join("\n    ")
        ));
    }
}

/// One instruction: once alone and once followed by the flag probe.
fn check_insn(insn: &[u8], rng: &mut Rng, states: usize, modes: &[Mode], stats: &mut Stats) {
    let mut probed = insn.to_vec();
    probed.extend(flag_probe());
    for k in 0..states {
        let st = random_state(rng);
        let mode = modes[k % modes.len()];
        compare(insn, &st, mode, stats);
        compare(&probed, &st, mode, stats);
    }
}

fn is_wide(hw1: u16) -> bool {
    hw1 >> 11 >= 0b11101
}

fn report(name: &str, stats: &Stats) {
    eprintln!(
        "{name}: {} cases, {} compared, {} failures",
        stats.cases,
        stats.compared,
        stats.failures.len()
    );
    let mut declined: Vec<_> = stats.declined.iter().collect();
    declined.sort_by_key(|d| std::cmp::Reverse(*d.1));
    for (why, n) in declined.iter().take(12) {
        eprintln!("  declined {n:6}  {}", &why[..why.len().min(110)]);
    }
    if !stats.gaps.is_empty() {
        eprintln!(
            "  accepted by the executor but not modelled by the reference: {:?}",
            stats.gaps
        );
    }
    assert!(
        stats.failures.is_empty(),
        "{name}: executor disagrees with the reference:\n  {}",
        stats.failures.join("\n  ")
    );
    assert!(
        stats.compared * 6 > stats.cases,
        "{name}: too few cases were comparable"
    );
}

fn scale() -> usize {
    std::env::var("CVERIF_FUZZ_ITERS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(1)
}

const MODES: &[Mode] = &[Mode::Concrete, Mode::Concrete, Mode::Pinned, Mode::PrivateStack];

/// Every 16-bit encoding.
#[test]
fn all_16bit_encodings() {
    let mut rng = Rng(0x1234_5678_9abc_def1);
    let mut stats = Stats::default();
    for hw in 0..0xe800u32 {
        // IT is covered by `it_blocks`: the flag probe would land inside the block.
        if hw & 0xff00 == 0xbf00 && hw & 0xf != 0 {
            continue;
        }
        check_insn(&(hw as u16).to_le_bytes(), &mut rng, scale(), MODES, &mut stats);
    }
    report("16-bit", &stats);
}

/// Random 32-bit encodings, biased towards the integer instruction space.
#[test]
fn random_32bit_encodings() {
    let mut rng = Rng(0x0fed_cba9_8765_4321);
    let mut stats = Stats::default();
    for _ in 0..60_000 * scale() {
        let x = rng.next();
        let mut hw1 = 0xe800 | (x as u16 & 0x1fff);
        if hw1 & 0x0400 != 0 && hw1 >> 11 == 0b11101 || hw1 >> 10 == 0b111111 {
            // coprocessor space: fold back into the integer encodings
            hw1 &= !0x0400;
        }
        let hw2 = (x >> 16) as u16;
        let mut code = hw1.to_le_bytes().to_vec();
        code.extend(hw2.to_le_bytes());
        check_insn(&code, &mut rng, 1, MODES, &mut stats);
    }
    report("32-bit", &stats);
}

/// 32-bit encodings one or two bits away from instructions compilers actually emit.
#[test]
fn near_compiler_32bit_encodings() {
    // A spread of real instructions (hw1, hw2) from compiled corpora.
    const SEEDS: &[(u16, u16)] = &[
        (0xf04f, 0x30ff),
        (0xf100, 0x0c01),
        (0xf1a0, 0x0210),
        (0xf5b0, 0x7f80),
        (0xf000, 0x0301),
        (0xf080, 0x0003),
        (0xf64c, 0x41cd),
        (0xf6cc, 0x41cc),
        (0xf2c0, 0x0100),
        (0xf240, 0x0100),
        (0xeb00, 0x0081),
        (0xeba0, 0x0043),
        (0xea4f, 0x1030),
        (0xea80, 0x0001),
        (0xea40, 0x2001),
        (0xea20, 0x0001),
        (0xea6f, 0x0000),
        (0xeb10, 0x0001),
        (0xeb41, 0x0103),
        (0xeb61, 0x0103),
        (0xebc0, 0x00c0),
        (0xebb0, 0x0f01),
        (0xea10, 0x0f01),
        (0xea90, 0x0f01),
        (0xfa00, 0xf001),
        (0xfa20, 0xf001),
        (0xfa40, 0xf001),
        (0xfa60, 0xf001),
        (0xfa01, 0xf000),
        (0xfa0f, 0xf080),
        (0xfa1f, 0xf080),
        (0xfa4f, 0xf080),
        (0xfa5f, 0xf080),
        (0xfa90, 0xf080),
        (0xfa90, 0xf0a0),
        (0xfab0, 0xf080),
        (0xfb00, 0xf001),
        (0xfb00, 0x2001),
        (0xfb00, 0x2011),
        (0xfb90, 0xf0f1),
        (0xfbb0, 0xf0f1),
        (0xfba0, 0x1201),
        (0xfb80, 0x0101),
        (0xfbe0, 0x1201),
        (0xfbc0, 0x0101),
        (0xfb10, 0xf001),
        (0xfb10, 0x2011),
        (0xfb50, 0xf001),
        (0xf8d0, 0x0004),
        (0xf8c0, 0x1004),
        (0xf890, 0x0001),
        (0xf880, 0x1001),
        (0xf8b0, 0x0002),
        (0xf8a0, 0x1002),
        (0xf990, 0x0001),
        (0xf9b0, 0x0002),
        (0xf850, 0x0021),
        (0xf840, 0x1022),
        (0xf850, 0x1b04),
        (0xf840, 0x1d04),
        (0xf85d, 0x7b04),
        (0xf84d, 0x7d04),
        (0xf810, 0x1f01),
        (0xf800, 0x1c01),
        (0xf8df, 0x0010),
        (0xf85f, 0x0004),
        (0xe9d0, 0x0102),
        (0xe9c0, 0x0102),
        (0xe8f0, 0x0102),
        (0xe9e0, 0x0102),
        (0xe8bd, 0x41f0),
        (0xe92d, 0x41f0),
        (0xe890, 0x000e),
        (0xe8a0, 0x000e),
        (0xe8b0, 0x000e),
        (0xe930, 0x000e),
        (0xe8df, 0xf001),
        (0xe8df, 0xf011),
        (0xf360, 0x0107),
        (0xf36f, 0x0107),
        (0xf3c0, 0x1003),
        (0xf340, 0x1003),
        (0xf300, 0x0007),
        (0xf380, 0x0008),
        (0xf000, 0x8002),
        (0xf000, 0xb802),
        (0xf000, 0xf802),
        (0xf43f, 0xaffe),
        (0xf1c0, 0x0000),
        (0xf140, 0x0000),
        (0xf160, 0x0000),
        (0xf110, 0x0f01),
        (0xf090, 0x0f01),
        (0xf010, 0x0f01),
        (0xf060, 0x0001),
        (0xf020, 0x0001),
        (0xf44f, 0x7080),
        (0xf04f, 0x4000),
        (0xf06f, 0x0001),
        (0xf20f, 0x0004),
        (0xf2af, 0x0004),
        (0xf200, 0x0001),
        (0xf2a0, 0x0001),
        (0xea5f, 0x0030),
        (0xea4f, 0x0070),
        (0xea5f, 0x0050),
        (0xf3af, 0x8000),
        (0xf7f0, 0xa000),
    ];
    let mut rng = Rng(0x7777_1111_3333_5555);
    let mut stats = Stats::default();
    for &(hw1, hw2) in SEEDS {
        assert!(is_wide(hw1));
        let word = (hw1 as u32) << 16 | hw2 as u32;
        let mut variants = vec![word];
        for b in 0..32 {
            variants.push(word ^ 1 << b);
        }
        for _ in 0..24 * scale() {
            variants.push(word ^ 1 << rng.below(32) ^ 1 << rng.below(32));
            // random registers and immediates in the low fields
            variants.push(word ^ (rng.next() as u32 & 0x000f_7fff));
        }
        for v in variants {
            if !is_wide((v >> 16) as u16) {
                continue;
            }
            let mut code = ((v >> 16) as u16).to_le_bytes().to_vec();
            code.extend((v as u16).to_le_bytes());
            check_insn(&code, &mut rng, 3, MODES, &mut stats);
        }
    }
    report("near-compiler 32-bit", &stats);
}

/// IT blocks of every shape over instructions whose behaviour depends on being inside one.
#[test]
fn it_blocks() {
    // 16-bit and 32-bit bodies: flag-setting ALU forms, compares, moves, loads, stores.
    const BODY: &[&[u16]] = &[
        &[0x1840],
        &[0x1a40],
        &[0x3001],
        &[0x3801],
        &[0x2105],
        &[0x4048],
        &[0x4008],
        &[0x4308],
        &[0x4388],
        &[0x43c8],
        &[0x4088],
        &[0x40c8],
        &[0x4108],
        &[0x41c8],
        &[0x4148],
        &[0x4188],
        &[0x4248],
        &[0x4348],
        &[0x0048],
        &[0x0848],
        &[0x1048],
        &[0x4288],
        &[0x42c8],
        &[0x4208],
        &[0x2800],
        &[0x4608],
        &[0x4440],
        &[0x6808],
        &[0x6008],
        &[0xb2c8],
        &[0xb248],
        &[0xf04f, 0x0801],
        &[0xf100, 0x0001],
        &[0xf110, 0x0001],
        &[0xeb00, 0x0041],
        &[0xeb10, 0x0041],
        &[0xfb00, 0xf001],
        &[0xf1b0, 0x0f05],
        &[0xea5f, 0x0040],
        &[0xf850, 0x1b04],
        &[0xbf00],
    ];
    let mut rng = Rng(0x2468_ace0_1357_9bdf);
    let mut stats = Stats::default();
    for cond in 0..14u16 {
        for mask in 1..16u16 {
            let len = 4 - mask.trailing_zeros() as usize;
            for _ in 0..6 * scale() {
                let mut code = (0xbf00 | cond << 4 | mask).to_le_bytes().to_vec();
                for _ in 0..len {
                    for hw in BODY[rng.below(BODY.len() as u64) as usize] {
                        code.extend(hw.to_le_bytes());
                    }
                }
                check_insn(&code, &mut rng, 2, MODES, &mut stats);
            }
        }
    }
    report("IT blocks", &stats);
}

/// Short straight-line sequences: flag producers feeding flag consumers.
#[test]
fn flag_chains() {
    const PRODUCERS: &[&[u16]] = &[
        &[0x1840],
        &[0x1a40],
        &[0x4288],
        &[0x42c8],
        &[0x4208],
        &[0x0048],
        &[0x0848],
        &[0x1048],
        &[0x4088],
        &[0x40c8],
        &[0x4108],
        &[0x41c8],
        &[0x4248],
        &[0x4348],
        &[0x2800],
        &[0xf110, 0x0f01],
        &[0xf1b0, 0x0f05],
        &[0xebb0, 0x0f41],
        &[0xea10, 0x7f01],
        &[0xea90, 0x0f31],
        &[0xea5f, 0x0031],
        &[0xea5f, 0x0071],
        &[0xfa10, 0xf001],
        &[0xfa30, 0xf001],
        &[0xfa50, 0xf001],
        &[0xfa70, 0xf001],
        &[0xf090, 0x4f00],
        &[0xf010, 0x0fff],
        &[0xf5b0, 0x3f80],
        &[0xeb50, 0x0001],
        &[0xeb70, 0x0001],
        &[0xf1d0, 0x0000],
        &[0xf150, 0x0000],
        &[0xf170, 0x0000],
        &[0xebd0, 0x0001],
    ];
    const CONSUMERS: &[&[u16]] = &[
        &[0x4148],
        &[0x4188],
        &[0xeb41, 0x0002],
        &[0xeb61, 0x0002],
        &[0xea4f, 0x0030],
        &[0xf141, 0x0100],
        &[0xf161, 0x0100],
        &[0xd000],
        &[0xd100],
        &[0xd200],
        &[0xd300],
        &[0xd400],
        &[0xd500],
        &[0xd600],
        &[0xd700],
        &[0xd800],
        &[0xd900],
        &[0xda00],
        &[0xdb00],
        &[0xdc00],
        &[0xdd00],
        &[0xf000, 0x8000],
        &[0xf040, 0x8000],
        &[0xf280, 0x8000],
        &[0xf2c0, 0x8000],
        &[0xf300, 0x8000],
        &[0xf340, 0x8000],
        &[0xf200, 0x8000],
        &[0xf240, 0x8000],
    ];
    let mut rng = Rng(0x0bad_cafe_dead_beef);
    let mut stats = Stats::default();
    for p in PRODUCERS {
        for c in CONSUMERS {
            let mut code = Vec::new();
            for hw in p.iter().chain(c.iter()) {
                code.extend(hw.to_le_bytes());
            }
            // A taken branch must skip something observable.
            code.extend(0x3701u16.to_le_bytes()); // adds r7, #1
            check_insn(&code, &mut rng, 4 * scale(), MODES, &mut stats);
        }
    }
    report("flag chains", &stats);
}

#[allow(dead_code)]
fn unused(bus: &mut dyn Bus) -> u8 {
    bus.read8(0)
}