Skip to content

Commit

Permalink
aslp: bit manipulation helpers (bytecodealliance#117)
Browse files Browse the repository at this point in the history
Adds library functions for manipulating opcode templates.

Updates avanhatt#36
  • Loading branch information
mmcloughlin authored Oct 5, 2024
1 parent 5ee5a8e commit f056b6d
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions cranelift/isle/veri/aslp/src/bits.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
use anyhow::{bail, Result};

#[derive(Clone)]
pub struct Bits {
pub segments: Vec<Segment>,
}

impl Bits {
pub fn empty() -> Self {
Bits {
segments: Vec::new(),
}
}

pub fn from_u32(x: u32) -> Self {
Bits {
segments: vec![Segment::from_u32(x)],
Expand All @@ -12,6 +21,45 @@ impl Bits {
pub fn width(&self) -> usize {
self.segments.iter().map(|s| s.width()).sum()
}

pub fn splice(base: &Bits, insert: &Bits, offset: usize) -> Result<Bits> {
let mut result = Bits::empty();
if offset > 0 {
let prefix = base.extract(0, offset)?;
result.append(prefix);
}
result.append(insert.clone());
if result.width() < base.width() {
let suffix = base.extract(result.width(), base.width())?;
result.append(suffix);
}
Ok(result)
}

pub fn append(&mut self, other: Bits) {
self.segments.extend(other.segments);
}

pub fn extract(&self, lo: usize, hi: usize) -> Result<Bits> {
let mut result = Bits::empty();
let mut offset = 0usize;
for segment in &self.segments {
// Intersection of this interval with extraction interval.
let start = std::cmp::max(lo, offset);
let end = std::cmp::min(hi, offset + segment.width());

// If the intersection is non-empty, add a segment.
if start < end {
result
.segments
.push(segment.extract(start - offset, end - offset)?);
}

// Advance offset.
offset += segment.width();
}
Ok(result)
}
}

impl std::fmt::Display for Bits {
Expand All @@ -28,6 +76,7 @@ impl std::fmt::Display for Bits {
}
}

#[derive(Clone)]
pub enum Segment {
Symbolic(String, usize),
Constant(u32, usize),
Expand All @@ -43,6 +92,25 @@ impl Segment {
Segment::Symbolic(_, w) | Segment::Constant(_, w) => *w,
}
}

pub fn extract(&self, lo: usize, hi: usize) -> Result<Segment> {
match *self {
Segment::Symbolic(_, w) => {
if !(lo == 0 && hi == w) {
bail!("symbolic segments must remain whole");
}
Ok(self.clone())
}
Segment::Constant(c, w) => {
if !(lo < hi && hi <= w) {
bail!("invalid extraction interval");
}
let w = hi - lo;
let mask = (1 << w) - 1;
Ok(Segment::Constant((c >> lo) & mask, w))
}
}
}
}

impl std::fmt::Display for Segment {
Expand Down

0 comments on commit f056b6d

Please sign in to comment.