From 12ed3fe9a780a9914b3f5727d921b4e419967549 Mon Sep 17 00:00:00 2001 From: Øyvind Harboe Date: Sat, 4 Dec 2021 18:45:16 +0100 Subject: [docs] add minimizing output bits recipe (#2278) Co-authored-by: Jack Koenig --- docs/src/cookbooks/cookbook.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'docs') diff --git a/docs/src/cookbooks/cookbook.md b/docs/src/cookbooks/cookbook.md index 4b2b088e..e23b158c 100644 --- a/docs/src/cookbooks/cookbook.md +++ b/docs/src/cookbooks/cookbook.md @@ -24,6 +24,7 @@ Please note that these examples make use of [Chisel's scala-style printing](../e * [How do I unpack a value ("reverse concatenation") like in Verilog?](#how-do-i-unpack-a-value-reverse-concatenation-like-in-verilog) * [How do I do subword assignment (assign to some bits in a UInt)?](#how-do-i-do-subword-assignment-assign-to-some-bits-in-a-uint) * [How do I create an optional I/O?](#how-do-i-create-an-optional-io) +* [How do I minimize the number of bits used in an output vector](#how-do-i-minimize-the-number-of-bits-used-in-an-output-vector) * Predictable Naming * [How do I get Chisel to name signals properly in blocks like when/withClockAndReset?](#how-do-i-get-chisel-to-name-signals-properly-in-blocks-like-whenwithclockandreset) * [How do I get Chisel to name the results of vector reads properly?](#how-do-i-get-chisel-to-name-the-results-of-vector-reads-properly) @@ -404,6 +405,34 @@ class ModuleWithOptionalIO(flag: Boolean) extends Module { } ``` +### How do I minimize the number of bits used in an output vector? + +Use inferred width and a `Seq` instead of a `Vec`: + +Consider: + +```scala mdoc:silent:reset +import chisel3._ + +// Count the number of set bits up to and including each bit position +class CountBits(width: Int) extends Module { + val bits = IO(Input(UInt(width.W))) + val countSequence = Seq.tabulate(width)(i => IO(Output(UInt()))) + val countVector = IO(Output(Vec(width, UInt()))) + countSequence.zipWithIndex.foreach { case (port, i) => + port := util.PopCount(bits(i, 0)) + } + countVector := countSequence +} +``` + +Unlike `Vecs` which represent a singular Chisel type and must have the same width for every element, +`Seq` is a purely Scala construct, so their elements are independent from the perspective of Chisel and can have different widths. + +```scala mdoc:verilog +chisel3.stage.ChiselStage.emitVerilog(new CountBits(4)) +``` + ## Predictable Naming ### How do I get Chisel to name signals properly in blocks like when/withClockAndReset? -- cgit v1.2.3