diff --git a/integration-tests/src/test/scala/chiselTests/util/experimental/algorithm/Bitwise.scala b/integration-tests/src/test/scala/chiselTests/util/experimental/algorithm/Bitwise.scala new file mode 100644 index 00000000000..503b2f83ff9 --- /dev/null +++ b/integration-tests/src/test/scala/chiselTests/util/experimental/algorithm/Bitwise.scala @@ -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))) + } + } +} \ No newline at end of file diff --git a/src/main/scala/chisel3/experimental/util/algorithm/Bitwise.scala b/src/main/scala/chisel3/experimental/util/algorithm/Bitwise.scala new file mode 100644 index 00000000000..a77346a3914 --- /dev/null +++ b/src/main/scala/chisel3/experimental/util/algorithm/Bitwise.scala @@ -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() +}