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
//! Decoding of RV64GC: the base integer instructions with the M, A, F, D,
//! C, Zicsr and Zifencei extensions. A compressed instruction decodes as
//! the instruction it stands for, two bytes long.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Width {
    Byte,
    Half,
    Word,
    Double,
}

impl Width {
    pub(crate) fn bytes(self) -> u8 {
        match self {
            Width::Byte => 1,
            Width::Half => 2,
            Width::Word => 4,
            Width::Double => 8,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Branch {
    Equal,
    NotEqual,
    Less,
    GreaterEqual,
    LessUnsigned,
    GreaterEqualUnsigned,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Alu {
    Add,
    Sub,
    ShiftLeft,
    Less,
    LessUnsigned,
    Xor,
    ShiftRight,
    ShiftRightArithmetic,
    Or,
    And,
    Multiply,
    MultiplyHigh,
    MultiplyHighSignedUnsigned,
    MultiplyHighUnsigned,
    Divide,
    DivideUnsigned,
    Remainder,
    RemainderUnsigned,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Atomic {
    Swap,
    Add,
    Xor,
    And,
    Or,
    Min,
    Max,
    MinUnsigned,
    MaxUnsigned,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Csr {
    Write,
    Set,
    Clear,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Precision {
    Single,
    Double,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloatBinary {
    Add,
    Sub,
    Multiply,
    Divide,
    Min,
    Max,
    /// The first operand with the sign of the second, of its opposite, or
    /// of the two signs' difference.
    Sign,
    SignNegated,
    SignXor,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloatCompare {
    Equal,
    Less,
    LessEqual,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Fused {
    /// `rs1 * rs2 + rs3`
    MultiplyAdd,
    /// `rs1 * rs2 - rs3`
    MultiplySub,
    /// `-(rs1 * rs2) + rs3`
    NegatedMultiplySub,
    /// `-(rs1 * rs2) - rs3`
    NegatedMultiplyAdd,
}

/// What an instruction does. `word` marks the forms that work on the low
/// 32 bits and sign-extend their result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Op {
    Lui,
    Auipc,
    Jal,
    Jalr,
    Branch(Branch),
    Load {
        width: Width,
        signed: bool,
    },
    Store(Width),
    /// `rd = rs1 op imm`
    Immediate {
        op: Alu,
        word: bool,
    },
    /// `rd = rs1 op rs2`
    Register {
        op: Alu,
        word: bool,
    },
    Fence,
    FenceInstructions,
    Ecall,
    Ebreak,
    /// A control and status register read and changed; `immediate` when
    /// the `rs1` field is the operand itself. `imm` is the register.
    Csr {
        op: Csr,
        immediate: bool,
    },
    LoadReserved(Width),
    StoreConditional(Width),
    Atomic {
        op: Atomic,
        width: Width,
    },
    FloatLoad(Precision),
    FloatStore(Precision),
    Fused {
        op: Fused,
        precision: Precision,
    },
    FloatBinary {
        op: FloatBinary,
        precision: Precision,
    },
    FloatSqrt(Precision),
    FloatCompare {
        op: FloatCompare,
        precision: Precision,
    },
    /// A float in `rs1` converted to the other precision, `to`.
    FloatConvert {
        to: Precision,
    },
    /// A float in `rs1` to an integer of 32 bits (`word`) or 64.
    FloatToInt {
        from: Precision,
        word: bool,
        signed: bool,
    },
    /// An integer in `rs1` to a float.
    IntToFloat {
        to: Precision,
        word: bool,
        signed: bool,
    },
    /// The bits of a float register to an integer one.
    FloatBits(Precision),
    /// The bits of an integer register to a float one.
    BitsToFloat(Precision),
    FloatClass(Precision),
}

/// One instruction: the registers are numbers from 0 to 31, of the integer
/// or the float file as `op` reads them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Instruction {
    pub op: Op,
    pub rd: u8,
    pub rs1: u8,
    pub rs2: u8,
    pub rs3: u8,
    pub imm: i64,
    /// The rounding mode field of a float instruction, or the two ordering
    /// bits of an atomic one.
    pub rounding: u8,
    /// 2 for a compressed instruction, else 4.
    pub length: u8,
}

impl Instruction {
    fn new(op: Op) -> Self {
        Self {
            op,
            rd: 0,
            rs1: 0,
            rs2: 0,
            rs3: 0,
            imm: 0,
            rounding: 0,
            length: 4,
        }
    }

    fn rd(mut self, rd: u32) -> Self {
        self.rd = (rd & 31) as u8;
        self
    }

    fn rs1(mut self, rs1: u32) -> Self {
        self.rs1 = (rs1 & 31) as u8;
        self
    }

    fn rs2(mut self, rs2: u32) -> Self {
        self.rs2 = (rs2 & 31) as u8;
        self
    }

    fn imm(mut self, imm: i64) -> Self {
        self.imm = imm;
        self
    }

    fn compressed(mut self) -> Self {
        self.length = 2;
        self
    }
}

/// The length in bytes of the instruction that starts with `low`, the
/// first 16 bits: 2, 4, or None for the longer encodings no standard
/// extension uses yet.
pub(crate) fn length(low: u16) -> Option<u8> {
    if low & 3 != 3 {
        Some(2)
    } else if low & 0x1c != 0x1c {
        Some(4)
    } else {
        None
    }
}

fn bits(word: u32, high: u32, low: u32) -> u32 {
    (word >> low) & ((1 << (high - low + 1)) - 1)
}

fn sign_extend(value: u32, width: u32) -> i64 {
    let shift = 64 - width;
    (i64::from(value) << shift) >> shift
}

fn alu(function: u32) -> Alu {
    match function & 7 {
        0 => Alu::Add,
        1 => Alu::ShiftLeft,
        2 => Alu::Less,
        3 => Alu::LessUnsigned,
        4 => Alu::Xor,
        5 => Alu::ShiftRight,
        6 => Alu::Or,
        _ => Alu::And,
    }
}

fn multiply(function: u32) -> Alu {
    match function & 7 {
        0 => Alu::Multiply,
        1 => Alu::MultiplyHigh,
        2 => Alu::MultiplyHighSignedUnsigned,
        3 => Alu::MultiplyHighUnsigned,
        4 => Alu::Divide,
        5 => Alu::DivideUnsigned,
        6 => Alu::Remainder,
        _ => Alu::RemainderUnsigned,
    }
}

/// Decodes the instruction at the start of `bytes`.
pub fn decode(bytes: &[u8]) -> Option<Instruction> {
    let Some(&[first, second]) = bytes.first_chunk::<2>() else {
        return None;
    };
    let low = u16::from_le_bytes([first, second]);
    match length(low) {
        Some(2) => decode_compressed(u32::from(low)).map(Instruction::compressed),
        Some(_) => {
            let Some(&word) = bytes.first_chunk::<4>() else {
                return None;
            };
            decode_word(u32::from_le_bytes(word))
        }
        None => None,
    }
}

fn decode_word(word: u32) -> Option<Instruction> {
    let rd = bits(word, 11, 7);
    let function = bits(word, 14, 12);
    let rs1 = bits(word, 19, 15);
    let rs2 = bits(word, 24, 20);
    let high = bits(word, 31, 25);
    let immediate = sign_extend(bits(word, 31, 20), 12);
    let store_offset = sign_extend(high << 5 | rd, 12);
    let three = |op| Instruction::new(op).rd(rd).rs1(rs1).rs2(rs2);
    let two = |op| Instruction::new(op).rd(rd).rs1(rs1).imm(immediate);
    Some(match word & 0x7f {
        0x37 => Instruction::new(Op::Lui)
            .rd(rd)
            .imm(i64::from((word & 0xffff_f000) as i32)),
        0x17 => Instruction::new(Op::Auipc)
            .rd(rd)
            .imm(i64::from((word & 0xffff_f000) as i32)),
        0x6f => {
            let offset = bits(word, 31, 31) << 20
                | bits(word, 19, 12) << 12
                | bits(word, 20, 20) << 11
                | bits(word, 30, 21) << 1;
            Instruction::new(Op::Jal)
                .rd(rd)
                .imm(sign_extend(offset, 21))
        }
        0x67 if function == 0 => two(Op::Jalr),
        0x63 => {
            let branch = match function {
                0 => Branch::Equal,
                1 => Branch::NotEqual,
                4 => Branch::Less,
                5 => Branch::GreaterEqual,
                6 => Branch::LessUnsigned,
                7 => Branch::GreaterEqualUnsigned,
                _ => return None,
            };
            let offset = bits(word, 31, 31) << 12
                | bits(word, 7, 7) << 11
                | bits(word, 30, 25) << 5
                | bits(word, 11, 8) << 1;
            Instruction::new(Op::Branch(branch))
                .rs1(rs1)
                .rs2(rs2)
                .imm(sign_extend(offset, 13))
        }
        0x03 => {
            let (width, signed) = match function {
                0 => (Width::Byte, true),
                1 => (Width::Half, true),
                2 => (Width::Word, true),
                3 => (Width::Double, true),
                4 => (Width::Byte, false),
                5 => (Width::Half, false),
                6 => (Width::Word, false),
                _ => return None,
            };
            two(Op::Load { width, signed })
        }
        0x23 => {
            let width = match function {
                0 => Width::Byte,
                1 => Width::Half,
                2 => Width::Word,
                3 => Width::Double,
                _ => return None,
            };
            Instruction::new(Op::Store(width))
                .rs1(rs1)
                .rs2(rs2)
                .imm(store_offset)
        }
        0x13 => {
            let shift = i64::from(bits(word, 25, 20));
            let op = match (function, bits(word, 31, 26)) {
                (1, 0) => Alu::ShiftLeft,
                (5, 0) => Alu::ShiftRight,
                (5, 0x10) => Alu::ShiftRightArithmetic,
                (1 | 5, _) => return None,
                _ => alu(function),
            };
            let instruction = two(Op::Immediate { op, word: false });
            if matches!(function, 1 | 5) {
                instruction.imm(shift)
            } else {
                instruction
            }
        }
        0x1b => {
            let op = match (function, high) {
                (0, _) => Alu::Add,
                (1, 0) => Alu::ShiftLeft,
                (5, 0) => Alu::ShiftRight,
                (5, 0x20) => Alu::ShiftRightArithmetic,
                _ => return None,
            };
            let instruction = two(Op::Immediate { op, word: true });
            if function == 0 {
                instruction
            } else {
                instruction.imm(i64::from(rs2))
            }
        }
        0x33 | 0x3b => {
            let word_form = word & 0x7f == 0x3b;
            let op = match (high, function) {
                (0, _) => alu(function),
                (0x20, 0) => Alu::Sub,
                (0x20, 5) => Alu::ShiftRightArithmetic,
                (1, _) => multiply(function),
                _ => return None,
            };
            if word_form
                && !matches!(
                    op,
                    Alu::Add
                        | Alu::Sub
                        | Alu::ShiftLeft
                        | Alu::ShiftRight
                        | Alu::ShiftRightArithmetic
                        | Alu::Multiply
                        | Alu::Divide
                        | Alu::DivideUnsigned
                        | Alu::Remainder
                        | Alu::RemainderUnsigned
                )
            {
                return None;
            }
            three(Op::Register {
                op,
                word: word_form,
            })
        }
        // The total-store-ordering fence and the pause hint are the two
        // fences with a mode field that is not zero.
        0x0f => match function {
            0 if rd == 0 && rs1 == 0 && (bits(word, 31, 28) == 0 || word == 0x8330_000f) => {
                Instruction::new(Op::Fence).imm(i64::from(bits(word, 31, 20)))
            }
            1 if word == 0x0000_100f => Instruction::new(Op::FenceInstructions),
            _ => return None,
        },
        0x73 => match function {
            0 if word == 0x0000_0073 => Instruction::new(Op::Ecall),
            0 if word == 0x0010_0073 => Instruction::new(Op::Ebreak),
            0 | 4 => return None,
            _ => {
                let op = match function & 3 {
                    1 => Csr::Write,
                    2 => Csr::Set,
                    _ => Csr::Clear,
                };
                Instruction::new(Op::Csr {
                    op,
                    immediate: function & 4 != 0,
                })
                .rd(rd)
                .rs1(rs1)
                .imm(i64::from(bits(word, 31, 20)))
            }
        },
        0x2f => {
            let width = match function {
                2 => Width::Word,
                3 => Width::Double,
                _ => return None,
            };
            let op = match bits(word, 31, 27) {
                0x02 if rs2 == 0 => {
                    let mut instruction = three(Op::LoadReserved(width));
                    instruction.rounding = bits(word, 26, 25) as u8;
                    return Some(instruction);
                }
                0x03 => {
                    let mut instruction = three(Op::StoreConditional(width));
                    instruction.rounding = bits(word, 26, 25) as u8;
                    return Some(instruction);
                }
                0x01 => Atomic::Swap,
                0x00 => Atomic::Add,
                0x04 => Atomic::Xor,
                0x0c => Atomic::And,
                0x08 => Atomic::Or,
                0x10 => Atomic::Min,
                0x14 => Atomic::Max,
                0x18 => Atomic::MinUnsigned,
                0x1c => Atomic::MaxUnsigned,
                _ => return None,
            };
            let mut instruction = three(Op::Atomic { op, width });
            instruction.rounding = bits(word, 26, 25) as u8;
            instruction
        }
        0x07 => match function {
            2 => two(Op::FloatLoad(Precision::Single)),
            3 => two(Op::FloatLoad(Precision::Double)),
            _ => return None,
        },
        0x27 => {
            let precision = match function {
                2 => Precision::Single,
                3 => Precision::Double,
                _ => return None,
            };
            Instruction::new(Op::FloatStore(precision))
                .rs1(rs1)
                .rs2(rs2)
                .imm(store_offset)
        }
        0x43 | 0x47 | 0x4b | 0x4f => {
            let precision = match bits(word, 26, 25) {
                0 => Precision::Single,
                1 => Precision::Double,
                _ => return None,
            };
            let op = match word & 0x7f {
                0x43 => Fused::MultiplyAdd,
                0x47 => Fused::MultiplySub,
                0x4b => Fused::NegatedMultiplySub,
                _ => Fused::NegatedMultiplyAdd,
            };
            if matches!(function, 5 | 6) {
                return None;
            }
            let mut instruction = three(Op::Fused { op, precision });
            instruction.rs3 = bits(word, 31, 27) as u8;
            instruction.rounding = function as u8;
            instruction
        }
        0x53 => {
            let precision = match high & 3 {
                0 => Precision::Single,
                1 => Precision::Double,
                _ => return None,
            };
            let binary = |op| Op::FloatBinary { op, precision };
            let compare = |op| Op::FloatCompare { op, precision };
            let word_form = rs2 & 2 == 0;
            let signed = rs2 & 1 == 0;
            let op = match (high >> 2, function, rs2) {
                (0x00, _, _) => binary(FloatBinary::Add),
                (0x01, _, _) => binary(FloatBinary::Sub),
                (0x02, _, _) => binary(FloatBinary::Multiply),
                (0x03, _, _) => binary(FloatBinary::Divide),
                (0x0b, _, 0) => Op::FloatSqrt(precision),
                (0x04, 0, _) => binary(FloatBinary::Sign),
                (0x04, 1, _) => binary(FloatBinary::SignNegated),
                (0x04, 2, _) => binary(FloatBinary::SignXor),
                (0x05, 0, _) => binary(FloatBinary::Min),
                (0x05, 1, _) => binary(FloatBinary::Max),
                (0x08, _, 1) if precision == Precision::Single => Op::FloatConvert {
                    to: Precision::Single,
                },
                (0x08, _, 0) if precision == Precision::Double => Op::FloatConvert {
                    to: Precision::Double,
                },
                (0x14, 0, _) => compare(FloatCompare::LessEqual),
                (0x14, 1, _) => compare(FloatCompare::Less),
                (0x14, 2, _) => compare(FloatCompare::Equal),
                (0x18, _, 0..=3) => Op::FloatToInt {
                    from: precision,
                    word: word_form,
                    signed,
                },
                (0x1a, _, 0..=3) => Op::IntToFloat {
                    to: precision,
                    word: word_form,
                    signed,
                },
                (0x1c, 0, 0) => Op::FloatBits(precision),
                (0x1c, 1, 0) => Op::FloatClass(precision),
                (0x1e, 0, 0) => Op::BitsToFloat(precision),
                _ => return None,
            };
            let rounded = match op {
                Op::FloatBinary { op, .. } => matches!(
                    op,
                    FloatBinary::Add
                        | FloatBinary::Sub
                        | FloatBinary::Multiply
                        | FloatBinary::Divide
                ),
                Op::FloatSqrt(_)
                | Op::FloatConvert { .. }
                | Op::FloatToInt { .. }
                | Op::IntToFloat { .. } => true,
                _ => false,
            };
            if rounded && matches!(function, 5 | 6) {
                return None;
            }
            let mut instruction = three(op);
            instruction.rounding = function as u8;
            instruction
        }
        _ => return None,
    })
}

fn decode_compressed(word: u32) -> Option<Instruction> {
    if word == 0 {
        return None;
    }
    const SP: u32 = 2;
    let function = bits(word, 15, 13);
    let full = bits(word, 11, 7);
    let other = bits(word, 6, 2);
    let near = bits(word, 9, 7) + 8;
    let near_other = bits(word, 4, 2) + 8;
    let immediate = sign_extend(bits(word, 12, 12) << 5 | other, 6);
    let shift = i64::from(bits(word, 12, 12) << 5 | other);
    let word_offset = bits(word, 12, 10) << 3 | bits(word, 6, 6) << 2 | bits(word, 5, 5) << 6;
    let double_offset = bits(word, 12, 10) << 3 | bits(word, 6, 5) << 6;
    let add = Op::Immediate {
        op: Alu::Add,
        word: false,
    };
    let load = |width| Op::Load {
        width,
        signed: true,
    };
    let register = |op, word| Op::Register { op, word };
    Some(match (word & 3, function) {
        (0, 0) => {
            let offset = bits(word, 12, 11) << 4
                | bits(word, 10, 7) << 6
                | bits(word, 6, 6) << 2
                | bits(word, 5, 5) << 3;
            if offset == 0 {
                return None;
            }
            Instruction::new(add)
                .rd(near_other)
                .rs1(SP)
                .imm(i64::from(offset))
        }
        (0, 1) => Instruction::new(Op::FloatLoad(Precision::Double))
            .rd(near_other)
            .rs1(near)
            .imm(i64::from(double_offset)),
        (0, 2) => Instruction::new(load(Width::Word))
            .rd(near_other)
            .rs1(near)
            .imm(i64::from(word_offset)),
        (0, 3) => Instruction::new(load(Width::Double))
            .rd(near_other)
            .rs1(near)
            .imm(i64::from(double_offset)),
        (0, 5) => Instruction::new(Op::FloatStore(Precision::Double))
            .rs1(near)
            .rs2(near_other)
            .imm(i64::from(double_offset)),
        (0, 6) => Instruction::new(Op::Store(Width::Word))
            .rs1(near)
            .rs2(near_other)
            .imm(i64::from(word_offset)),
        (0, 7) => Instruction::new(Op::Store(Width::Double))
            .rs1(near)
            .rs2(near_other)
            .imm(i64::from(double_offset)),
        (1, 0) => Instruction::new(add).rd(full).rs1(full).imm(immediate),
        (1, 1) if full != 0 => Instruction::new(Op::Immediate {
            op: Alu::Add,
            word: true,
        })
        .rd(full)
        .rs1(full)
        .imm(immediate),
        (1, 2) => Instruction::new(add).rd(full).imm(immediate),
        (1, 3) if full == SP => {
            let offset = bits(word, 12, 12) << 9
                | bits(word, 6, 6) << 4
                | bits(word, 5, 5) << 6
                | bits(word, 4, 3) << 7
                | bits(word, 2, 2) << 5;
            if offset == 0 {
                return None;
            }
            Instruction::new(add)
                .rd(SP)
                .rs1(SP)
                .imm(sign_extend(offset, 10))
        }
        (1, 3) => {
            if immediate == 0 {
                return None;
            }
            Instruction::new(Op::Lui).rd(full).imm(immediate << 12)
        }
        (1, 4) => match bits(word, 11, 10) {
            0 => Instruction::new(Op::Immediate {
                op: Alu::ShiftRight,
                word: false,
            })
            .rd(near)
            .rs1(near)
            .imm(shift),
            1 => Instruction::new(Op::Immediate {
                op: Alu::ShiftRightArithmetic,
                word: false,
            })
            .rd(near)
            .rs1(near)
            .imm(shift),
            2 => Instruction::new(Op::Immediate {
                op: Alu::And,
                word: false,
            })
            .rd(near)
            .rs1(near)
            .imm(immediate),
            _ => {
                let op = match (bits(word, 12, 12), bits(word, 6, 5)) {
                    (0, 0) => register(Alu::Sub, false),
                    (0, 1) => register(Alu::Xor, false),
                    (0, 2) => register(Alu::Or, false),
                    (0, _) => register(Alu::And, false),
                    (_, 0) => register(Alu::Sub, true),
                    (_, 1) => register(Alu::Add, true),
                    _ => return None,
                };
                Instruction::new(op).rd(near).rs1(near).rs2(near_other)
            }
        },
        (1, 5) => {
            let offset = bits(word, 12, 12) << 11
                | bits(word, 11, 11) << 4
                | bits(word, 10, 9) << 8
                | bits(word, 8, 8) << 10
                | bits(word, 7, 7) << 6
                | bits(word, 6, 6) << 7
                | bits(word, 5, 3) << 1
                | bits(word, 2, 2) << 5;
            Instruction::new(Op::Jal).imm(sign_extend(offset, 12))
        }
        (1, 6 | 7) => {
            let offset = bits(word, 12, 12) << 8
                | bits(word, 11, 10) << 3
                | bits(word, 6, 5) << 6
                | bits(word, 4, 3) << 1
                | bits(word, 2, 2) << 5;
            let branch = if function == 6 {
                Branch::Equal
            } else {
                Branch::NotEqual
            };
            Instruction::new(Op::Branch(branch))
                .rs1(near)
                .imm(sign_extend(offset, 9))
        }
        (2, 0) => Instruction::new(Op::Immediate {
            op: Alu::ShiftLeft,
            word: false,
        })
        .rd(full)
        .rs1(full)
        .imm(shift),
        (2, 1 | 3) => {
            let offset = bits(word, 12, 12) << 5 | bits(word, 6, 5) << 3 | bits(word, 4, 2) << 6;
            let op = if function == 1 {
                Op::FloatLoad(Precision::Double)
            } else if full == 0 {
                return None;
            } else {
                load(Width::Double)
            };
            Instruction::new(op).rd(full).rs1(SP).imm(i64::from(offset))
        }
        (2, 2) if full != 0 => {
            let offset = bits(word, 12, 12) << 5 | bits(word, 6, 4) << 2 | bits(word, 3, 2) << 6;
            Instruction::new(load(Width::Word))
                .rd(full)
                .rs1(SP)
                .imm(i64::from(offset))
        }
        (2, 4) => match (bits(word, 12, 12), full, other) {
            (0, 0, 0) => return None,
            (0, _, 0) => Instruction::new(Op::Jalr).rs1(full),
            (0, _, _) => Instruction::new(add).rd(full).rs1(other),
            (_, 0, 0) => Instruction::new(Op::Ebreak),
            (_, _, 0) => Instruction::new(Op::Jalr).rd(1).rs1(full),
            _ => Instruction::new(register(Alu::Add, false))
                .rd(full)
                .rs1(full)
                .rs2(other),
        },
        (2, 5 | 7) => {
            let offset = bits(word, 12, 10) << 3 | bits(word, 9, 7) << 6;
            let op = if function == 5 {
                Op::FloatStore(Precision::Double)
            } else {
                Op::Store(Width::Double)
            };
            Instruction::new(op)
                .rs1(SP)
                .rs2(other)
                .imm(i64::from(offset))
        }
        (2, 6) => {
            let offset = bits(word, 12, 9) << 2 | bits(word, 8, 7) << 6;
            Instruction::new(Op::Store(Width::Word))
                .rs1(SP)
                .rs2(other)
                .imm(i64::from(offset))
        }
        _ => return None,
    })
}