disc-v 0.1.3

A RISC-V disassembler
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
// Copyright (c) 2026 Christopher Swenson
// Licensed under the Apache-2.0 license.

//! Extensions, and sets of them.

use core::fmt;

/// Defines [`Extension`], with each variant's name in an ISA string, and
/// [`Extension::ALL`], so that every variant is in `ALL`.
macro_rules! extensions {
    ($($(#[$doc:meta])* $variant:ident = $name:literal,)*) => {
        /// A RISC-V extension that defines instructions disc-v can decode.
        ///
        /// Extensions that define no instructions, such as Zkt or Sstc, are
        /// not listed; [`Decoder::from_march`](crate::Decoder::from_march)
        /// accepts and ignores them.
        ///
        /// The instructions of the vector and vendor extensions are only
        /// decoded with the `vector`, `vendor-thead` and `vendor-corev`
        /// Cargo features, which are on by default.
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
        #[non_exhaustive]
        pub enum Extension {
            $($(#[$doc])* $variant,)*
        }

        impl Extension {
            /// Every extension, in declaration order.
            const ALL: &[Extension] = &[$(Extension::$variant),*];

            /// The extension's name in an ISA string, such as `"zba"` or
            /// `"m"`.
            pub const fn name(self) -> &'static str {
                match self {
                    $(Extension::$variant => $name,)*
                }
            }
        }
    };
}

extensions! {
    /// The RV32E and RV64E bases: only registers x0-x15 exist, so
    /// instructions that use x16-x31 are reserved. This restricts the base
    /// ISA rather than adding instructions, so it is not in
    /// [`Extensions::DEFAULT`].
    E = "e",
    /// Integer multiplication and division.
    M = "m",
    /// Atomic instructions.
    A = "a",
    /// Single-precision floating point.
    F = "f",
    /// Double-precision floating point. Implies F.
    D = "d",
    /// Quad-precision floating point. Implies D.
    Q = "q",
    /// Compressed instructions: Zca, and Zcf and Zcd when F and D are
    /// enabled.
    C = "c",
    /// Compressed integer instructions.
    Zca = "zca",
    /// Compressed single-precision loads and stores (RV32 only). Implies Zca
    /// and F.
    Zcf = "zcf",
    /// Compressed double-precision loads and stores. Implies Zca and D.
    Zcd = "zcd",
    /// Compressed push, pop and register moves (`cm.push`, ...). Implies
    /// Zca, and conflicts with Zcd.
    Zcmp = "zcmp",
    /// Compressed table jumps (`cm.jt`, `cm.jalt`). Implies Zca and Zicsr,
    /// and conflicts with Zcd.
    Zcmt = "zcmt",
    /// Load and store register pairs on RV32 (`ld`, `sd`).
    Zilsd = "zilsd",
    /// Compressed load and store register pairs on RV32 (`c.ld`, `c.sd`,
    /// ...). Implies Zilsd and Zca, and conflicts with Zcf.
    Zclsd = "zclsd",
    /// Vectors.
    V = "v",
    /// The hypervisor extension.
    H = "h",
    /// Control and status register instructions.
    Zicsr = "zicsr",
    /// `fence.i`.
    Zifencei = "zifencei",
    /// Integer conditional operations (`czero.*`).
    Zicond = "zicond",
    /// Load-acquire and store-release (`lw.aq`, `sw.rl`, ...).
    Zalasr = "zalasr",
    /// Atomic compare-and-swap (`amocas.*`). Implies A.
    Zacas = "zacas",
    /// Byte and halfword atomics (`amoadd.b`, ...). Implies A.
    Zabha = "zabha",
    /// Wait-on-reservation-set (`wrs.*`).
    Zawrs = "zawrs",
    /// Cache-block management (`cbo.clean`, `cbo.flush`, `cbo.inval`).
    Zicbom = "zicbom",
    /// Cache-block zero (`cbo.zero`).
    Zicboz = "zicboz",
    /// Cache-block prefetch hints (`prefetch.*`).
    Zicbop = "zicbop",
    /// Non-temporal locality hints (`ntl.*`).
    Zihintntl = "zihintntl",
    /// The `pause` hint.
    Zihintpause = "zihintpause",
    /// May-be-operations (`mop.r.N`, `mop.rr.N`).
    Zimop = "zimop",
    /// Compressed may-be-operations (`c.mop.N`). Implies C.
    Zcmop = "zcmop",
    /// Shadow stacks (`sspush`, `sspopchk`, `ssrdp`, `ssamoswap.*`).
    /// Implies Zimop.
    Zicfiss = "zicfiss",
    /// Landing pads (`lpad`).
    Zicfilp = "zicfilp",
    /// Address generation (`sh1add`, ...).
    Zba = "zba",
    /// Basic bit manipulation (`andn`, `clz`, ...).
    Zbb = "zbb",
    /// Carry-less multiplication (`clmul`, ...).
    Zbc = "zbc",
    /// Single-bit instructions (`bset`, ...).
    Zbs = "zbs",
    /// Bit manipulation for cryptography (`pack`, `brev8`, ...). It also
    /// provides several Zbb instructions, such as `rol` and `rev8`.
    Zbkb = "zbkb",
    /// Carry-less multiplication for cryptography: Zbc's `clmul` and
    /// `clmulh`.
    Zbkc = "zbkc",
    /// Crossbar permutations (`xperm4`, `xperm8`).
    Zbkx = "zbkx",
    /// AES decryption.
    Zknd = "zknd",
    /// AES encryption.
    Zkne = "zkne",
    /// SHA-256 and SHA-512.
    Zknh = "zknh",
    /// SM4.
    Zksed = "zksed",
    /// SM3.
    Zksh = "zksh",
    /// Simple compressed instructions (`c.lbu`, `c.mul`, ...). Implies C.
    Zcb = "zcb",
    /// Half-precision floating point. Implies Zfhmin.
    Zfh = "zfh",
    /// Minimal half-precision floating point: loads, stores and
    /// conversions. Implies F.
    Zfhmin = "zfhmin",
    /// Additional floating-point instructions (`fli`, `fround`, ...).
    /// Implies F.
    Zfa = "zfa",
    /// Conversions between BFloat16 and single precision. Implies F.
    Zfbfmin = "zfbfmin",
    /// Single-precision floating point in the integer registers: F's
    /// instructions except its loads, stores and moves, with integer
    /// register operands. Conflicts with F (and so with the extensions that
    /// imply it, such as D, Zfa and C's Zcf).
    Zfinx = "zfinx",
    /// Double-precision floating point in the integer registers (register
    /// pairs on RV32). Implies Zfinx.
    Zdinx = "zdinx",
    /// Half-precision floating point in the integer registers. Implies
    /// Zhinxmin.
    Zhinx = "zhinx",
    /// Minimal half-precision floating point in the integer registers: the
    /// conversions. Implies Zfinx.
    Zhinxmin = "zhinxmin",
    /// Vector BFloat16 conversions. Implies V.
    Zvfbfmin = "zvfbfmin",
    /// Vector BFloat16 widening multiply-add. Implies Zvfbfmin.
    Zvfbfwma = "zvfbfwma",
    /// Vector bit manipulation. Implies V.
    Zvbb = "zvbb",
    /// Vector carry-less multiplication. Implies V.
    Zvbc = "zvbc",
    /// Vector GCM/GMAC. Implies V.
    Zvkg = "zvkg",
    /// Vector AES. Implies V.
    Zvkned = "zvkned",
    /// Vector SHA-256. Implies V.
    Zvknha = "zvknha",
    /// Vector SHA-256 and SHA-512. Implies Zvknha, whose instructions it
    /// shares.
    Zvknhb = "zvknhb",
    /// Vector SM4. Implies V.
    Zvksed = "zvksed",
    /// Vector SM3. Implies V.
    Zvksh = "zvksh",
    /// Fine-grained address-translation cache invalidation (`sinval.vma`,
    /// ...).
    Svinval = "svinval",
    /// Debug mode (`dret`).
    Sdext = "sdext",
    /// Resumable non-maskable interrupts (`mnret`).
    Smrnmi = "smrnmi",
    /// Control-transfer records (`sctrclr`).
    Ssctr = "ssctr",
    /// T-Head address calculation (`th.addsl`).
    XTheadBa = "xtheadba",
    /// T-Head basic bit manipulation (`th.ext`, `th.ff1`, `th.rev`, ...).
    XTheadBb = "xtheadbb",
    /// T-Head single-bit test (`th.tst`).
    XTheadBs = "xtheadbs",
    /// T-Head cache management (`th.dcache.*`, `th.icache.*`, `th.l2cache.*`).
    XTheadCmo = "xtheadcmo",
    /// T-Head conditional moves (`th.mveqz`, `th.mvnez`).
    XTheadCondMov = "xtheadcondmov",
    /// T-Head indexed floating-point loads and stores (`th.flrw`, ...).
    /// Implies F.
    XTheadFMemIdx = "xtheadfmemidx",
    /// T-Head moves of the upper half of a double-precision register on RV32
    /// (`th.fmv.hw.x`, `th.fmv.x.hw`). Implies D.
    XTheadFmv = "xtheadfmv",
    /// T-Head interrupt register saving (`th.ipush`, `th.ipop`).
    XTheadInt = "xtheadint",
    /// T-Head multiply-accumulate (`th.mula`, ...).
    XTheadMac = "xtheadmac",
    /// T-Head indexed loads and stores, and loads and stores that update the
    /// base register (`th.lrw`, `th.lbia`, ...).
    XTheadMemIdx = "xtheadmemidx",
    /// T-Head load and store pairs (`th.lwd`, `th.sdd`, ...).
    XTheadMemPair = "xtheadmempair",
    /// T-Head synchronization (`th.sync`, `th.sfence.vmas`, ...).
    XTheadSync = "xtheadsync",
    /// CORE-V ALU operations (`cv.abs`, `cv.clip`, `cv.addn`, ...).
    XCValu = "xcvalu",
    /// CORE-V branches with an immediate (`cv.beqimm`, `cv.bneimm`).
    XCVbi = "xcvbi",
    /// CORE-V bit manipulation (`cv.extract`, `cv.bset`, `cv.cnt`, ...).
    XCVbitmanip = "xcvbitmanip",
    /// CORE-V event load (`cv.elw`).
    XCVelw = "xcvelw",
    /// CORE-V multiply-accumulate (`cv.mac`, `cv.mulsn`, ...).
    XCVmac = "xcvmac",
    /// CORE-V post-increment and register-offset loads and stores (`cv.lw`,
    /// `cv.sw`, ...).
    XCVmem = "xcvmem",
    /// CORE-V packed SIMD (`cv.add.h`, `cv.dotsp.b`, ...).
    XCVsimd = "xcvsimd",
}

// Extensions are a bit set in a u128.
const _: () = assert!(Extension::ALL.len() <= 128);

impl Extension {
    /// The extension named `name` in an ISA string, ignoring case.
    pub fn from_name(name: &str) -> Option<Extension> {
        Extension::ALL
            .iter()
            .copied()
            .find(|e| e.name().eq_ignore_ascii_case(name))
    }

    /// The extensions this one implies.
    const fn implies(self) -> &'static [Extension] {
        use Extension::*;
        match self {
            D | Zfhmin | Zfa | Zfbfmin => &[F],
            C | Zcb | Zcmop | Zcmp => &[Zca],
            Zcf => &[Zca, F],
            Zcd => &[Zca, D],
            Zcmt => &[Zca, Zicsr],
            Zclsd => &[Zilsd, Zca],
            Q => &[D],
            Zfh => &[Zfhmin],
            Zdinx | Zhinxmin => &[Zfinx],
            Zhinx => &[Zhinxmin],
            Zacas | Zabha => &[A],
            Zicfiss => &[Zimop],
            Zvbb | Zvbc | Zvkg | Zvkned | Zvknha | Zvksed | Zvksh | Zvfbfmin => &[V],
            Zvfbfwma => &[Zvfbfmin],
            Zvknhb => &[Zvknha],
            XTheadFMemIdx => &[F],
            XTheadFmv => &[D],
            _ => &[],
        }
    }

    /// The extension that provides this one's instructions with their
    /// floating-point operands in the integer registers, such as Zfinx for
    /// F, or the extension itself if there is none.
    pub(crate) const fn in_x_registers(self) -> Extension {
        use Extension::*;
        match self {
            F => Zfinx,
            D => Zdinx,
            Zfh => Zhinx,
            Zfhmin => Zhinxmin,
            ext => ext,
        }
    }

    /// Whether this is a vendor extension, such as XTheadBa.
    pub(crate) const fn is_vendor(self) -> bool {
        matches!(self.name().as_bytes(), [b'x', ..])
    }

    const fn bit(self) -> u128 {
        1 << self as u32
    }
}

impl fmt::Display for Extension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// A set of [`Extension`]s.
///
/// Adding an extension also adds the extensions it implies (D implies F),
/// and removing one also removes the extensions that imply it (removing F
/// removes D).
///
/// ```
/// use disc_v::{Extension, Extensions};
///
/// let exts = Extensions::GC.with(Extension::Zba).without(Extension::D);
/// assert!(exts.contains(Extension::F));
/// assert!(!exts.contains(Extension::Q));
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Extensions(u128);

impl Extensions {
    /// No extensions: only the base integer ISA.
    pub const EMPTY: Extensions = Extensions(0);

    /// Every supported standard extension that does not conflict with
    /// another. Vendor extensions are left out: they use the custom opcode
    /// spaces, which each vendor's cores use differently. This is what
    /// [`decode`](fn@crate::decode) and the other free functions use.
    pub const DEFAULT: Extensions = {
        let mut set = Extensions::of(Extension::ALL)
            .without(Extension::E)
            .without(Extension::Zcmp)
            .without(Extension::Zcmt)
            .without(Extension::Zclsd)
            .without(Extension::Zfinx);
        let mut i = 0;
        while i < Extension::ALL.len() {
            if Extension::ALL[i].is_vendor() {
                set = set.without(Extension::ALL[i]);
            }
            i += 1;
        }
        set
    };

    /// G and C: IMAFD, Zicsr, Zifencei and C, as in RV32GC and RV64GC.
    pub const GC: Extensions = {
        use Extension::*;
        Extensions::of(&[M, A, F, D, C, Zicsr, Zifencei])
    };

    /// The extensions of the RVA23U64 profile that define instructions.
    pub const RVA23U64: Extensions = {
        use Extension::*;
        Extensions::of(&[
            M,
            A,
            F,
            D,
            C,
            V,
            Zicsr,
            Zicond,
            Zawrs,
            Zicbom,
            Zicboz,
            Zicbop,
            Zihintntl,
            Zihintpause,
            Zimop,
            Zcmop,
            Zba,
            Zbb,
            Zbs,
            Zcb,
            Zfhmin,
            Zfa,
            Zvbb,
        ])
    };

    /// The extensions of the RVA23S64 profile that define instructions:
    /// RVA23U64, Zifencei, Svinval and H.
    pub const RVA23S64: Extensions = {
        use Extension::*;
        Extensions::RVA23U64.union(Extensions::of(&[Zifencei, Svinval, H]))
    };

    /// Every T-Head vendor extension (XThead*), as in T-Head's C9xx cores.
    pub const XTHEAD: Extensions = {
        use Extension::*;
        Extensions::of(&[
            XTheadBa,
            XTheadBb,
            XTheadBs,
            XTheadCmo,
            XTheadCondMov,
            XTheadFMemIdx,
            XTheadFmv,
            XTheadInt,
            XTheadMac,
            XTheadMemIdx,
            XTheadMemPair,
            XTheadSync,
        ])
    };

    /// Every CORE-V vendor extension (XCV*), as in the OpenHW Group's
    /// CV32E40P core.
    pub const XCV: Extensions = {
        use Extension::*;
        Extensions::of(&[XCValu, XCVbi, XCVbitmanip, XCVelw, XCVmac, XCVmem, XCVsimd])
    };

    /// The extensions in `exts`, and the extensions they imply.
    pub const fn of(exts: &[Extension]) -> Extensions {
        let mut set = Extensions::EMPTY;
        let mut i = 0;
        while i < exts.len() {
            set = set.with(exts[i]);
            i += 1;
        }
        set
    }

    /// Whether the set contains `ext`.
    pub const fn contains(self, ext: Extension) -> bool {
        self.0 & ext.bit() != 0
    }

    /// The set with `ext` and the extensions it implies added.
    pub const fn with(self, ext: Extension) -> Extensions {
        if self.contains(ext) {
            return self;
        }
        let mut set = Extensions(self.0 | ext.bit());
        let implied = ext.implies();
        let mut i = 0;
        while i < implied.len() {
            set = set.with(implied[i]);
            i += 1;
        }
        // C includes Zcf and Zcd when F and D are enabled.
        if set.contains(Extension::C) && set.contains(Extension::F) {
            set = set.with(Extension::Zcf);
        }
        if set.contains(Extension::C) && set.contains(Extension::D) {
            set = set.with(Extension::Zcd);
        }
        set
    }

    /// The set with `ext` and the extensions that imply it removed.
    ///
    /// C is a bundle of Zca and (with F and D) Zcf and Zcd: removing C
    /// removes every compressed instruction, and removing Zcf or Zcd removes
    /// C but keeps Zca.
    pub const fn without(self, ext: Extension) -> Extensions {
        let mut set = self.remove(ext);
        match ext {
            Extension::C => set = set.remove(Extension::Zca),
            Extension::Zcf | Extension::Zcd => set.0 &= !Extension::C.bit(),
            _ => {}
        }
        set
    }

    /// The set with `ext` and the extensions that imply it removed.
    const fn remove(self, ext: Extension) -> Extensions {
        let mut set = Extensions(self.0 & !ext.bit());
        let mut i = 0;
        while i < Extension::ALL.len() {
            let other = Extension::ALL[i];
            let implied = other.implies();
            let mut j = 0;
            while j < implied.len() {
                if implied[j] as u32 == ext as u32 && set.contains(other) {
                    set = set.remove(other);
                }
                j += 1;
            }
            i += 1;
        }
        set
    }

    /// The extensions in either set (and the extensions they imply
    /// together, such as Zcd for C and D).
    pub const fn union(self, other: Extensions) -> Extensions {
        let mut set = self;
        let mut i = 0;
        while i < Extension::ALL.len() {
            if other.contains(Extension::ALL[i]) {
                set = set.with(Extension::ALL[i]);
            }
            i += 1;
        }
        set
    }

    /// The extensions in the set, in declaration order.
    pub fn iter(self) -> impl Iterator<Item = Extension> {
        Extension::ALL
            .iter()
            .copied()
            .filter(move |&e| self.contains(e))
    }
}

impl Default for Extensions {
    /// [`Extensions::DEFAULT`].
    fn default() -> Self {
        Extensions::DEFAULT
    }
}

impl fmt::Debug for Extensions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}

impl From<Extension> for Extensions {
    fn from(ext: Extension) -> Self {
        Extensions::EMPTY.with(ext)
    }
}

impl<const N: usize> From<[Extension; N]> for Extensions {
    fn from(exts: [Extension; N]) -> Self {
        Extensions::of(&exts)
    }
}

impl From<&[Extension]> for Extensions {
    fn from(exts: &[Extension]) -> Self {
        Extensions::of(exts)
    }
}

impl FromIterator<Extension> for Extensions {
    fn from_iter<I: IntoIterator<Item = Extension>>(iter: I) -> Self {
        iter.into_iter().fold(Extensions::EMPTY, Extensions::with)
    }
}

impl core::ops::BitOr for Extensions {
    type Output = Extensions;

    fn bitor(self, other: Extensions) -> Extensions {
        self.union(other)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn names_round_trip() {
        for &ext in Extension::ALL {
            assert_eq!(Extension::from_name(ext.name()), Some(ext));
        }
        assert_eq!(Extension::from_name("ZBA"), Some(Extension::Zba));
        assert_eq!(Extension::from_name("XTheadBa"), Some(Extension::XTheadBa));
        assert_eq!(Extension::from_name("xventanacondops"), None);
    }

    #[test]
    fn all_lists_every_extension_once() {
        let mut bits = 0u128;
        for (i, &ext) in Extension::ALL.iter().enumerate() {
            assert_eq!(ext as usize, i);
            bits |= ext.bit();
        }
        assert_eq!(bits.count_ones() as usize, Extension::ALL.len());
    }

    #[test]
    fn implications() {
        use Extension::*;
        let set = Extensions::EMPTY.with(Q);
        assert_eq!(set, Extensions::of(&[F, D, Q]));
        assert_eq!(set.without(F), Extensions::EMPTY);
        assert_eq!(set.without(Q), Extensions::of(&[F, D]));
        assert!(Extensions::from(Zvknhb).contains(V));
    }
}