src/main/scala/chipsldpc/TwoMin.scala

Source from the repository checkout used to build these docs. Line numbers link to individual source lines.

 1package chipsldpc
 2
 3import chisel3._
 4// Purely combinational circuit for finding the two smallest incoming magnitudes at a check node, preserving duplicates.
 5// This lets the check compute the minimum excluding each recipient using one shared circuit.
 6object TwoMinLogic {
 7  private final case class Candidate(value: UInt, losers: Seq[UInt])
 8
 9  private def minimum(values: Seq[UInt]): UInt =
10    if (values.size == 1) values.head
11    else minimum(values.grouped(2).map {
12      case Seq(a, b) => Mux(a <= b, a, b)
13      case Seq(a)    => a
14    }.toSeq)
15
16  def apply(values: Seq[UInt]): (UInt, UInt) = {
17    require(values.size >= 2)
18    val bits = values.head.getWidth
19    val paddedSize = 1 << BigInt(values.size - 1).bitLength
20    val maximum = ((BigInt(1) << bits) - 1).U(bits.W)
21    val leaves = values.map(Candidate(_, Seq.empty)) ++
22      Seq.fill(paddedSize - values.size)(Candidate(maximum, Seq.empty))
23
24    def tournament(level: Seq[Candidate]): Candidate =
25      if (level.size == 1) level.head
26      else tournament(level.grouped(2).map { pair =>
27        val left = pair.head
28        val right = pair(1)
29        val leftWins = left.value <= right.value
30        val history = left.losers.indices.map(i => Mux(leftWins, left.losers(i), right.losers(i)))
31        Candidate(
32          Mux(leftWins, left.value, right.value),
33          history :+ Mux(leftWins, right.value, left.value),
34        )
35      }.toSeq)
36
37    val winner = tournament(leaves)
38    (winner.value, minimum(winner.losers))
39  }
40}
41
42final class TwoMin(degree: Int, bits: Int) extends RawModule {
43  require(degree >= 2 && bits > 0)
44  val inputs = IO(Input(Vec(degree, UInt(bits.W))))
45  val result = IO(Output(new MinPair(bits)))
46  val (first, second) = TwoMinLogic(inputs.toSeq)
47  result.first := first
48  result.second := second
49}