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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The arithmetic the data processing groups share, DDI 0403E.b A2.2.1, A5.3.2 and A7.4.2.
//!
//! What acts on a register's value emits Cranelift IR through the [`Emitter`]. What only reads
//! the encoding runs at translate time. A carry, an overflow or a saturation comes back as 0 or 1
//! in an `i32`, the way [`Emitter::flag`] gives a flag, so you can hand it to
//! [`Emitter::set_flag`] as it is.

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

use super::{Emitter, bits};

/// `SRType`, D6.3.6: the shift an instruction applies to a register.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ShiftType {
    Lsl,
    Lsr,
    Asr,
    Ror,
    Rrx,
}

/// `AddWithCarry(x, y, carry_in)`, A2.2.1, answering `(result, carry_out, overflow)`.
///
/// Subtract with `AddWithCarry(x, NOT(y), '1')`, and the carry is NOT borrow.
pub(crate) fn add_with_carry(
    e: &mut Emitter<'_, '_>,
    x: Value,
    y: Value,
    carry_in: Value,
) -> (Value, Value, Value) {
    let carry = e.b.ins().uextend(types::I64, carry_in);
    let (ux, uy) = (
        e.b.ins().uextend(types::I64, x),
        e.b.ins().uextend(types::I64, y),
    );
    let unsigned_sum = e.b.ins().iadd(ux, uy);
    let unsigned_sum = e.b.ins().iadd(unsigned_sum, carry);
    let (sx, sy) = (
        e.b.ins().sextend(types::I64, x),
        e.b.ins().sextend(types::I64, y),
    );
    let signed_sum = e.b.ins().iadd(sx, sy);
    let signed_sum = e.b.ins().iadd(signed_sum, carry);
    let result = e.b.ins().ireduce(types::I32, unsigned_sum);
    let unsigned = e.b.ins().uextend(types::I64, result);
    let carry_out = e.b.ins().icmp(IntCC::NotEqual, unsigned, unsigned_sum);
    let signed = e.b.ins().sextend(types::I64, result);
    let overflow = e.b.ins().icmp(IntCC::NotEqual, signed, signed_sum);
    (result, word(e, carry_out), word(e, overflow))
}

/// `DecodeImmShift(type, imm5)`, A7.4.2: an immediate of 0 is a shift by 32 for LSR and ASR,
/// and RRX for ROR.
pub(crate) fn decode_imm_shift(shift_type: u32, imm5: u32) -> (ShiftType, u32) {
    match (shift_type & 0b11, imm5) {
        (0b00, _) => (ShiftType::Lsl, imm5),
        (0b01, 0) => (ShiftType::Lsr, 32),
        (0b01, _) => (ShiftType::Lsr, imm5),
        (0b10, 0) => (ShiftType::Asr, 32),
        (0b10, _) => (ShiftType::Asr, imm5),
        (_, 0) => (ShiftType::Rrx, 1),
        _ => (ShiftType::Ror, imm5),
    }
}

/// `Shift_C(value, type, amount, carry_in)`, A7.4.2, by an amount the encoding fixes, answering
/// `(result, carry_out)`. The shifts are A2.2.1's `LSL_C`, `LSR_C`, `ASR_C`, `ROR_C` and `RRX_C`.
///
/// # Panics
///
/// When `shift_type` is RRX and `amount` isn't 1, which `Shift_C` asserts.
pub(crate) fn shift_c(
    e: &mut Emitter<'_, '_>,
    value: Value,
    shift_type: ShiftType,
    amount: u32,
    carry_in: Value,
) -> (Value, Value) {
    assert!(
        shift_type != ShiftType::Rrx || amount == 1,
        "Shift_C only shifts RRX by one"
    );
    if amount == 0 {
        return (value, carry_in);
    }
    let shift = i64::from(amount);
    match (shift_type, amount) {
        (ShiftType::Lsl, 1..=31) => {
            let result = e.b.ins().ishl_imm_s(value, shift);
            (result, bit(e, value, 32 - amount))
        }
        (ShiftType::Lsl, 32) => (e.constant(0), bit(e, value, 0)),
        (ShiftType::Lsr, 1..=31) => {
            let result = e.b.ins().ushr_imm_u(value, shift);
            (result, bit(e, value, amount - 1))
        }
        (ShiftType::Lsr, 32) => (e.constant(0), bit(e, value, 31)),
        (ShiftType::Lsl | ShiftType::Lsr, _) => (e.constant(0), e.constant(0)),
        (ShiftType::Asr, 1..=31) => {
            let result = e.b.ins().sshr_imm_u(value, shift);
            (result, bit(e, value, amount - 1))
        }
        // Past 31 every bit the extension shifts in, and out, is the sign.
        (ShiftType::Asr, _) => {
            let result = e.b.ins().sshr_imm_u(value, 31);
            (result, bit(e, value, 31))
        }
        (ShiftType::Ror, _) => {
            let result = e.b.ins().rotr_imm_u(value, i64::from(amount % 32));
            (result, bit(e, result, 31))
        }
        (ShiftType::Rrx, _) => {
            let top = e.b.ins().ishl_imm_s(carry_in, 31);
            let rest = e.b.ins().ushr_imm_u(value, 1);
            let result = e.b.ins().bor(top, rest);
            (result, bit(e, value, 0))
        }
    }
}

/// `Shift_C(value, type, amount, carry_in)`, A7.4.2, by an amount in a register, answering
/// `(result, carry_out)`. The register shifts pass `UInt(R[m]<7:0>)` as `amount`, and any
/// unsigned `amount` gives what the pseudocode does.
///
/// # Panics
///
/// When `shift_type` is RRX, which no register shift is.
pub(crate) fn shift_c_register(
    e: &mut Emitter<'_, '_>,
    value: Value,
    shift_type: ShiftType,
    amount: Value,
    carry_in: Value,
) -> (Value, Value) {
    // Every amount past 33 gives what 33 does for LSL, LSR and ASR, and the host's shifts only
    // take amounts below 64, so you clamp first and extend to 64 bits, where nothing is lost.
    let clamped = e.constant(33);
    let clamped = e.b.ins().umin(amount, clamped);
    let (result, carry) = match shift_type {
        ShiftType::Lsl => {
            let wide = e.b.ins().uextend(types::I64, value);
            let extended = e.b.ins().ishl(wide, clamped);
            let result = e.b.ins().ireduce(types::I32, extended);
            let carry = e.b.ins().ushr_imm_u(extended, 32);
            let carry = e.b.ins().ireduce(types::I32, carry);
            (result, e.b.ins().band_imm_s(carry, 1))
        }
        ShiftType::Lsr | ShiftType::Asr => {
            let wide = if shift_type == ShiftType::Lsr {
                e.b.ins().uextend(types::I64, value)
            } else {
                e.b.ins().sextend(types::I64, value)
            };
            // One zero below bit 0 puts `extended_x<shift-1>` at bit 0 after the shift.
            let below = e.b.ins().ishl_imm_s(wide, 1);
            let (shifted, out) = if shift_type == ShiftType::Lsr {
                (
                    e.b.ins().ushr(wide, clamped),
                    e.b.ins().ushr(below, clamped),
                )
            } else {
                (
                    e.b.ins().sshr(wide, clamped),
                    e.b.ins().sshr(below, clamped),
                )
            };
            let result = e.b.ins().ireduce(types::I32, shifted);
            let carry = e.b.ins().ireduce(types::I32, out);
            (result, e.b.ins().band_imm_s(carry, 1))
        }
        // `m = shift MOD N` is what the host's rotate does with its amount.
        ShiftType::Ror => {
            let result = e.b.ins().rotr(value, amount);
            (result, bit(e, result, 31))
        }
        ShiftType::Rrx => panic!("no register shift is RRX"),
    };
    let zero = e.b.ins().icmp_imm_s(IntCC::Equal, amount, 0);
    (
        e.b.ins().select(zero, value, result),
        e.b.ins().select(zero, carry_in, carry),
    )
}

/// `ThumbExpandImm_C(imm12, carry_in)`, A5.3.2, at translate time: the constant, and the carry
/// out when the encoding decides it. `None` means the carry out is the carry in.
pub(crate) fn thumb_expand_imm_c(imm12: u32) -> (u32, Option<u32>) {
    if bits(imm12, 11, 10) != 0b00 {
        let unrotated = 0x80 | bits(imm12, 6, 0);
        let imm32 = unrotated.rotate_right(bits(imm12, 11, 7));
        return (imm32, Some(imm32 >> 31));
    }
    let imm8 = bits(imm12, 7, 0);
    // A zero byte that's replicated is UNPREDICTABLE, A5.3.2. You get the zero the replication
    // makes, the simplest thing the pseudocode suggests.
    let imm32 = match bits(imm12, 9, 8) {
        0b00 => imm8,
        0b01 => imm8 << 16 | imm8,
        0b10 => imm8 << 24 | imm8 << 8,
        _ => imm8 * 0x0101_0101,
    };
    (imm32, None)
}

/// `SignedSatQ(i, N)`, A2.2.1, answering `(result<N-1:0>, saturated)`.
///
/// `i` is the pseudocode's unbounded integer as an `i64`, which every caller's fits, a sum of two
/// 32-bit values included. The result is the N bits zero-extended, so SSAT sign-extends it.
///
/// # Panics
///
/// When `n` isn't 1 to 32.
pub(crate) fn signed_sat_q(e: &mut Emitter<'_, '_>, i: Value, n: u32) -> (Value, Value) {
    assert!(
        (1..=32).contains(&n),
        "SignedSatQ saturates to 1 to 32 bits"
    );
    let largest = (1_i64 << (n - 1)) - 1;
    let (result, saturated) = saturate(e, i, -largest - 1, largest);
    let result = if n < 32 {
        e.b.ins()
            .band_imm_u(result, i64::from(u32::MAX >> (32 - n)))
    } else {
        result
    };
    (result, saturated)
}

/// `UnsignedSatQ(i, N)`, A2.2.1, answering `(result<N-1:0>, saturated)`, with `i` as
/// [`signed_sat_q`] takes it. USAT saturates to 0 bits, which always gives 0.
///
/// # Panics
///
/// When `n` is past 32.
pub(crate) fn unsigned_sat_q(e: &mut Emitter<'_, '_>, i: Value, n: u32) -> (Value, Value) {
    assert!(n <= 32, "UnsignedSatQ saturates to at most 32 bits");
    saturate(e, i, 0, (1_i64 << n) - 1)
}

/// `i` held to `smallest..=largest`, as an `i32`, and whether it had to be.
fn saturate(e: &mut Emitter<'_, '_>, i: Value, smallest: i64, largest: i64) -> (Value, Value) {
    let above = e.b.ins().icmp_imm_s(IntCC::SignedGreaterThan, i, largest);
    let below = e.b.ins().icmp_imm_s(IntCC::SignedLessThan, i, smallest);
    let high = e.b.ins().iconst(types::I64, largest);
    let low = e.b.ins().iconst(types::I64, smallest);
    let result = e.b.ins().select(below, low, i);
    let result = e.b.ins().select(above, high, result);
    let saturated = e.b.ins().bor(above, below);
    (e.b.ins().ireduce(types::I32, result), word(e, saturated))
}

/// Bit `n` of `value`, as 0 or 1.
fn bit(e: &mut Emitter<'_, '_>, value: Value, n: u32) -> Value {
    let shifted = e.b.ins().ushr_imm_u(value, i64::from(n));
    e.b.ins().band_imm_s(shifted, 1)
}

/// A comparison's `i8` as 0 or 1 in an `i32`.
fn word(e: &mut Emitter<'_, '_>, truth: Value) -> Value {
    e.b.ins().uextend(types::I32, truth)
}

#[cfg(test)]
mod tests {
    //! The functions that emit IR are checked by evaluating what they emit, since nothing runs one
    //! alone on the processor. The evaluator knows only the operations they use, each as
    //! Cranelift's docs define it.

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

    use super::*;

    /// Emits `build` into a function of its own and answers the values it gives.
    fn emitted(build: impl FnOnce(&mut Emitter<'_, '_>) -> Vec<Value>) -> Vec<u32> {
        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);
        let values = build(&mut e);
        values
            .into_iter()
            .map(|value| u32::try_from(evaluate(&builder.func.dfg, value)).unwrap())
            .collect()
    }

    fn evaluate(dfg: &DataFlowGraph, value: Value) -> u64 {
        let value = dfg.resolve_aliases(value);
        let ValueDef::Result(inst, _) = dfg.value_def(value) else {
            panic!("{value} isn't an instruction's");
        };
        let width = dfg.value_type(value).bits();
        let args = dfg.inst_args(inst);
        let arg = |k: usize| evaluate(dfg, args[k]);
        let arg_width = |k: usize| dfg.value_type(args[k]).bits();
        let sign = |x: u64, width: u32| (x << (64 - width)).cast_signed() >> (64 - width);
        // Cranelift's shifts and rotates take their amount modulo the value's width.
        let amount = |k: usize| arg(k) % u64::from(width);
        let answer = match dfg.insts[inst] {
            InstructionData::UnaryImm { imm, .. } => imm.bits().cast_unsigned(),
            InstructionData::IntCompare { cond, .. } => {
                let (x, y) = (arg(0), arg(1));
                let (sx, sy) = (sign(x, arg_width(0)), sign(y, arg_width(1)));
                u64::from(match cond {
                    IntCC::Equal => x == y,
                    IntCC::NotEqual => x != y,
                    IntCC::SignedGreaterThan => sx > sy,
                    IntCC::SignedLessThan => sx < sy,
                    other => panic!("the evaluator doesn't compare {other}"),
                })
            }
            data => match data.opcode() {
                Opcode::Iadd => arg(0).wrapping_add(arg(1)),
                Opcode::Band => arg(0) & arg(1),
                Opcode::Bor => arg(0) | arg(1),
                Opcode::Ishl => arg(0) << amount(1),
                Opcode::Ushr => arg(0) >> amount(1),
                Opcode::Sshr => (sign(arg(0), width) >> amount(1)).cast_unsigned(),
                Opcode::Rotr => match amount(1) {
                    0 => arg(0),
                    by => arg(0) >> by | arg(0) << (u64::from(width) - by),
                },
                Opcode::Umin => arg(0).min(arg(1)),
                Opcode::Uextend | Opcode::Ireduce => arg(0),
                Opcode::Sextend => sign(arg(0), arg_width(0)).cast_unsigned(),
                Opcode::Select => {
                    if arg(0) == 0 {
                        arg(2)
                    } else {
                        arg(1)
                    }
                }
                other => panic!("the evaluator doesn't run {other}"),
            },
        };
        answer & (u64::MAX >> (64 - width))
    }

    fn add(x: u32, y: u32, carry_in: u32) -> (u32, u32, u32) {
        let answer = emitted(|e| {
            let (x, y, carry_in) = (e.constant(x), e.constant(y), e.constant(carry_in));
            let (result, carry, overflow) = add_with_carry(e, x, y, carry_in);
            vec![result, carry, overflow]
        });
        (answer[0], answer[1], answer[2])
    }

    fn shift(value: u32, shift_type: ShiftType, amount: u32, carry_in: u32) -> (u32, u32) {
        let answer = emitted(|e| {
            let (value, carry_in) = (e.constant(value), e.constant(carry_in));
            let (result, carry) = shift_c(e, value, shift_type, amount, carry_in);
            vec![result, carry]
        });
        (answer[0], answer[1])
    }

    fn shift_register(value: u32, shift_type: ShiftType, amount: u32, carry_in: u32) -> (u32, u32) {
        let answer = emitted(|e| {
            let (value, carry_in) = (e.constant(value), e.constant(carry_in));
            let amount = e.constant(amount);
            let (result, carry) = shift_c_register(e, value, shift_type, amount, carry_in);
            vec![result, carry]
        });
        (answer[0], answer[1])
    }

    fn signed(i: i64, n: u32) -> (u32, u32) {
        let answer = emitted(|e| {
            let i = e.b.ins().iconst(types::I64, i);
            let (result, saturated) = signed_sat_q(e, i, n);
            vec![result, saturated]
        });
        (answer[0], answer[1])
    }

    fn unsigned(i: i64, n: u32) -> (u32, u32) {
        let answer = emitted(|e| {
            let i = e.b.ins().iconst(types::I64, i);
            let (result, saturated) = unsigned_sat_q(e, i, n);
            vec![result, saturated]
        });
        (answer[0], answer[1])
    }

    /// A2.2.1: the carry is unsigned overflow and V signed overflow, for additions and for
    /// subtractions as `x + NOT(y) + 1`, where the carry is NOT borrow.
    #[test]
    fn add_with_carry_sets_carry_and_overflow_as_the_pseudocode_does() {
        assert_eq!(add(1, 2, 0), (3, 0, 0));
        assert_eq!(add(0xFFFF_FFFF, 1, 0), (0, 1, 0));
        assert_eq!(add(0x7FFF_FFFF, 1, 0), (0x8000_0000, 0, 1));
        assert_eq!(add(0x8000_0000, 0x8000_0000, 0), (0, 1, 1));
        assert_eq!(add(0xFFFF_FFFF, 0, 1), (0, 1, 0), "the carry in adds one");
        assert_eq!(add(0x7FFF_FFFF, 0, 1), (0x8000_0000, 0, 1));
        assert_eq!(add(0xFFFF_FFFF, 0xFFFF_FFFF, 1), (0xFFFF_FFFF, 1, 0));
        assert_eq!(add(5, !5, 1), (0, 1, 0), "5 - 5 borrows nothing");
        assert_eq!(add(3, !5, 1), (0xFFFF_FFFE, 0, 0), "3 - 5 borrows");
        assert_eq!(add(0x8000_0000, !1, 1), (0x7FFF_FFFF, 1, 1));
        assert_eq!(add(5, !5, 0), (0xFFFF_FFFF, 0, 0), "SBC takes one more");
    }

    /// A7.4.2's table: a zero immediate shifts LSR and ASR by 32, and makes ROR an RRX by one.
    #[test]
    fn decode_imm_shift_reads_a_zero_immediate_as_the_manual_says() {
        assert_eq!(decode_imm_shift(0b00, 0), (ShiftType::Lsl, 0));
        assert_eq!(decode_imm_shift(0b00, 31), (ShiftType::Lsl, 31));
        assert_eq!(decode_imm_shift(0b01, 0), (ShiftType::Lsr, 32));
        assert_eq!(decode_imm_shift(0b01, 7), (ShiftType::Lsr, 7));
        assert_eq!(decode_imm_shift(0b10, 0), (ShiftType::Asr, 32));
        assert_eq!(decode_imm_shift(0b10, 31), (ShiftType::Asr, 31));
        assert_eq!(decode_imm_shift(0b11, 0), (ShiftType::Rrx, 1));
        assert_eq!(decode_imm_shift(0b11, 1), (ShiftType::Ror, 1));
    }

    /// A2.2.1's `LSL_C` to `RRX_C` through A7.4.2's `Shift_C`, by amounts an encoding fixes.
    #[test]
    fn a_constant_shift_gives_the_result_and_carry_the_pseudocode_does() {
        use ShiftType::{Asr, Lsl, Lsr, Ror, Rrx};
        assert_eq!(shift(0x1234_5678, Lsl, 0, 1), (0x1234_5678, 1), "keeps C");
        assert_eq!(shift(0x1234_5678, Lsl, 0, 0), (0x1234_5678, 0));
        assert_eq!(shift(0x8000_0001, Lsl, 1, 0), (2, 1));
        assert_eq!(shift(3, Lsl, 31, 0), (0x8000_0000, 1));
        assert_eq!(shift(1, Lsl, 31, 1), (0x8000_0000, 0));
        assert_eq!(shift(1, Lsl, 32, 0), (0, 1));
        assert_eq!(shift(0xFFFF_FFFF, Lsl, 33, 1), (0, 0));
        assert_eq!(shift(0x8000_0001, Lsr, 1, 0), (0x4000_0000, 1));
        assert_eq!(shift(0x8000_0000, Lsr, 31, 0), (1, 0));
        assert_eq!(shift(0x8000_0000, Lsr, 32, 0), (0, 1));
        assert_eq!(shift(0xFFFF_FFFF, Lsr, 33, 1), (0, 0));
        assert_eq!(shift(0x8000_0008, Asr, 4, 0), (0xF800_0000, 1));
        assert_eq!(shift(0x4000_0000, Asr, 30, 1), (1, 0));
        assert_eq!(shift(0x8000_0000, Asr, 32, 0), (0xFFFF_FFFF, 1));
        assert_eq!(shift(0x7FFF_FFFF, Asr, 32, 1), (0, 0));
        assert_eq!(shift(0x8000_0000, Asr, 40, 0), (0xFFFF_FFFF, 1));
        assert_eq!(shift(0x12, Ror, 4, 1), (0x2000_0001, 0));
        assert_eq!(shift(1, Ror, 1, 0), (0x8000_0000, 1));
        assert_eq!(shift(0x8000_0000, Ror, 32, 0), (0x8000_0000, 1), "MOD 32");
        assert_eq!(shift(3, Rrx, 1, 1), (0x8000_0001, 1));
        assert_eq!(shift(3, Rrx, 1, 0), (1, 1));
        assert_eq!(shift(2, Rrx, 1, 0), (1, 0));
    }

    /// The register shifts take `R[m]<7:0>`, so amounts past 32 reach `Shift_C`.
    #[test]
    fn a_register_shift_gives_the_result_and_carry_the_pseudocode_does() {
        use ShiftType::{Asr, Lsl, Lsr, Ror};
        for shift_type in [Lsl, Lsr, Asr, Ror] {
            assert_eq!(
                shift_register(0x8000_0001, shift_type, 0, 1),
                (0x8000_0001, 1),
                "{shift_type:?} by 0 keeps C"
            );
        }
        assert_eq!(shift_register(0x8000_0001, Lsl, 1, 0), (2, 1));
        assert_eq!(shift_register(3, Lsl, 31, 0), (0x8000_0000, 1));
        assert_eq!(shift_register(1, Lsl, 32, 0), (0, 1));
        assert_eq!(shift_register(0xFFFF_FFFF, Lsl, 33, 1), (0, 0));
        assert_eq!(shift_register(0xFFFF_FFFF, Lsl, 255, 1), (0, 0));
        assert_eq!(shift_register(0x8000_0001, Lsr, 1, 0), (0x4000_0000, 1));
        assert_eq!(shift_register(0x8000_0000, Lsr, 32, 0), (0, 1));
        assert_eq!(shift_register(0xFFFF_FFFF, Lsr, 33, 1), (0, 0));
        assert_eq!(shift_register(0xFFFF_FFFF, Lsr, 200, 1), (0, 0));
        assert_eq!(shift_register(0x8000_0008, Asr, 4, 0), (0xF800_0000, 1));
        assert_eq!(shift_register(0x8000_0000, Asr, 32, 0), (0xFFFF_FFFF, 1));
        assert_eq!(shift_register(0x8000_0000, Asr, 255, 0), (0xFFFF_FFFF, 1));
        assert_eq!(shift_register(0x7FFF_FFFF, Asr, 255, 1), (0, 0));
        assert_eq!(shift_register(0x12, Ror, 4, 1), (0x2000_0001, 0));
        assert_eq!(shift_register(0x8000_0000, Ror, 32, 0), (0x8000_0000, 1));
        assert_eq!(shift_register(1, Ror, 33, 0), (0x8000_0000, 1));
        assert_eq!(shift_register(0x7FFF_FFFF, Ror, 64, 1), (0x7FFF_FFFF, 0));
        assert_eq!(shift_register(0x12, Ror, 0xFFFF_FFE4, 1), (0x2000_0001, 0));
        assert_eq!(shift_register(1, Lsl, 0xFFFF_FFFF, 1), (0, 0));
    }

    /// Both forms are `Shift_C`, so they agree wherever an encoding could give the same amount.
    #[test]
    fn a_register_shift_agrees_with_a_constant_one() {
        for shift_type in [
            ShiftType::Lsl,
            ShiftType::Lsr,
            ShiftType::Asr,
            ShiftType::Ror,
        ] {
            for amount in 0..=40 {
                for value in [0x8000_0001, 0x7FFF_FFFE, 0xA5A5_5A5A] {
                    for carry_in in [0, 1] {
                        assert_eq!(
                            shift_register(value, shift_type, amount, carry_in),
                            shift(value, shift_type, amount, carry_in),
                            "{shift_type:?} {value:#x} by {amount}, C {carry_in}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    #[should_panic(expected = "Shift_C only shifts RRX by one")]
    fn rrx_by_more_than_one_is_refused() {
        shift(1, ShiftType::Rrx, 2, 0);
    }

    /// A5.3.2's table, and the carry its rotated forms set from bit 31.
    #[test]
    fn thumb_expand_imm_gives_the_table_s_constants_and_carry() {
        assert_eq!(thumb_expand_imm_c(0x0AB), (0x0000_00AB, None));
        assert_eq!(thumb_expand_imm_c(0x1AB), (0x00AB_00AB, None));
        assert_eq!(thumb_expand_imm_c(0x2AB), (0xAB00_AB00, None));
        assert_eq!(thumb_expand_imm_c(0x3AB), (0xABAB_ABAB, None));
        assert_eq!(thumb_expand_imm_c(0x455), (0xD500_0000, Some(1)), "01000");
        assert_eq!(thumb_expand_imm_c(0x480), (0x4000_0000, Some(0)), "01001");
        assert_eq!(thumb_expand_imm_c(0x500), (0x2000_0000, Some(0)), "01010");
        assert_eq!(thumb_expand_imm_c(0xF7F), (0x0000_03FC, Some(0)), "11110");
        assert_eq!(thumb_expand_imm_c(0xFFF), (0x0000_01FE, Some(0)), "11111");
    }

    /// A zero byte replicated is UNPREDICTABLE, A5.3.2, and gives the zero the replication makes.
    #[test]
    fn thumb_expand_imm_replicates_a_zero_byte_to_zero() {
        for imm12 in [0x100, 0x200, 0x300] {
            assert_eq!(thumb_expand_imm_c(imm12), (0, None));
        }
    }

    /// A2.2.1's `SignedSatQ`: the range is `-(2^(N-1))` to `2^(N-1) - 1`, and the result is its
    /// low N bits.
    #[test]
    fn signed_sat_q_holds_to_the_range_and_says_when() {
        assert_eq!(signed(127, 8), (0x7F, 0));
        assert_eq!(signed(128, 8), (0x7F, 1));
        assert_eq!(signed(-128, 8), (0x80, 0));
        assert_eq!(signed(-129, 8), (0x80, 1));
        assert_eq!(signed(0, 1), (0, 0));
        assert_eq!(signed(-1, 1), (1, 0));
        assert_eq!(signed(1, 1), (0, 1));
        assert_eq!(signed(-2, 1), (1, 1));
        assert_eq!(signed(0x7FFF_FFFF, 32), (0x7FFF_FFFF, 0));
        assert_eq!(signed(0x8000_0000, 32), (0x7FFF_FFFF, 1));
        assert_eq!(signed(-0x8000_0000, 32), (0x8000_0000, 0));
        assert_eq!(signed(-0x8000_0001, 32), (0x8000_0000, 1));
        assert_eq!(signed(-0x1_0000_0000, 32), (0x8000_0000, 1));
        assert_eq!(signed(-5, 16), (0xFFFB, 0));
    }

    /// A2.2.1's `UnsignedSatQ`: the range is 0 to `2^N - 1`.
    #[test]
    fn unsigned_sat_q_holds_to_the_range_and_says_when() {
        assert_eq!(unsigned(255, 8), (0xFF, 0));
        assert_eq!(unsigned(256, 8), (0xFF, 1));
        assert_eq!(unsigned(0, 8), (0, 0));
        assert_eq!(unsigned(-1, 8), (0, 1));
        assert_eq!(unsigned(0, 0), (0, 0));
        assert_eq!(unsigned(5, 0), (0, 1));
        assert_eq!(unsigned(-1, 0), (0, 1));
        assert_eq!(unsigned(0x7FFF_FFFF, 31), (0x7FFF_FFFF, 0));
        assert_eq!(unsigned(0x8000_0000, 31), (0x7FFF_FFFF, 1));
        assert_eq!(unsigned(-0x8000_0000, 31), (0, 1));
        assert_eq!(unsigned(0x1_FFFF, 16), (0xFFFF, 1));
    }
}