Skip to content

Commit

Permalink
Add LSBOr and MSBOr utility
Browse files Browse the repository at this point in the history
  • Loading branch information
CircuitCoder committed Feb 10, 2022
1 parent 024847d commit 5b3576c
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import chisel3._
import chisel3.util._
import chisel3.experimental.util.algorithm._
import chiseltest._
import chiseltest.formal._
import org.scalatest.flatspec.AnyFlatSpec

class LSBOrTestModule(width: Int) extends Module {
val input = IO(Input(UInt(width.W)))

var lsb = false.B
val vec = for(b <- input.asBools) yield {
val cur = b || lsb
lsb = cur
cur
}
val ref = VecInit(vec).asUInt

val testee = LSBOr(input)

assert(testee === ref)
}

class MSBOrTestModule(width: Int) extends Module {
val input = IO(Input(UInt(width.W)))

val ref = Reverse(LSBOr(Reverse(input)))
val testee = MSBOr(input)

assert(testee === ref)
}

class LSBMSBOrTest extends AnyFlatSpec with ChiselScalatestTester with Formal {
"LSBOr" should "correctly computes" in {
for(i <- 1 to 16) {
verify(new LSBOrTestModule(i), Seq(BoundedCheck(1)))
}
}

"MSBOr" should "correctly computes" in {
for(i <- 1 to 16) {
verify(new MSBOrTestModule(i), Seq(BoundedCheck(1)))
}
}
}
29 changes: 29 additions & 0 deletions src/main/scala/chisel3/experimental/util/algorithm/Bitwise.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package chisel3.experimental.util.algorithm

import chisel3._

/** Map each bits to logical or of itself and all bits less siginificant than it.
* @example {{{
* LSBOr("b00001000".U) // Returns "b11111000".U
* LSBOr("b00010100".U) // Returns "b11111100".U
* LSBOr("b00000000".U) // Returns "b00000000".U
* }}}
*/
object LSBOr {
def apply(data: UInt): UInt = VecInit(Seq.tabulate(data.getWidth) { i: Int =>
VecInit(data.asBools().dropRight(data.getWidth - i - 1)).asUInt().orR()
}).asUInt()
}

/** Map each bits to logical or of itself and all bits more siginificant than it.
* @example {{{
* MSBOr("b00001000".U) // Returns "b00001111".U
* MSBOr("b00010100".U) // Returns "b00011111".U
* MSBOr("b00000000".U) // Returns "b00000000".U
* }}}
*/
object MSBOr {
def apply(data: UInt): UInt = VecInit(Seq.tabulate(data.getWidth) { i: Int =>
VecInit(data.asBools().drop(i)).asUInt().orR()
}).asUInt()
}

0 comments on commit 5b3576c

Please sign in to comment.