How to freely assign values to vec type variables in chisel? - chisel

I defined some vec variables.
val r_parameters = Wire(Vec(RANK, UInt(log2Ceil(RANK).W)))
val test0 = Wire(Vec(RANK, UInt(width.W)))
val test1 = Wire(Vec(RANK, UInt(width.W)))
I try to use for loop for assignment.
for (i <- 0 to RANK-1)
{
test0(r_parameters(i)) := test1(i)
}
variable 'r_parameters' is from rom or ram. If parameter 'RANK' is 4, r_parameters has the form as '0 3 2 1' or '0 1 2 3'. Thus all test0 are assigned. But firrtl compiler reports that test0 is not fully initialized.

I think the problem is that the firrtl compiler cannot be sure that every element of test0 has been initialized to something. I have filled out your examples, with values supplied and a couple of stylistic changes to this.
class Wires extends MultiIOModule {
val RANK = 4
val bits = 8
// set to 0, 3, 2, 1
val r_parameters = VecInit(Seq(0, 3, 2, 1).map(_.U) )
val test0 = Wire(Vec(RANK, UInt(bits.W)))
// Give values to test1
val test1 = VecInit(Seq.tabulate(RANK) { i => i.U } )
// Wire test1 into test using the map provided by r_parameters
for (i <- test0.indices) {
test0(r_parameters(i)) := test1(i)
}
}
If you dump the emitted firrtl with
println((new ChiselStage).emitFirrtl(new Wires))
You will see
test0[r_parameters[0]] <= test1[0] #[MemBank.scala 56:28]
test0[r_parameters[1]] <= test1[1] #[MemBank.scala 56:28]
test0[r_parameters[2]] <= test1[2] #[MemBank.scala 56:28]
test0[r_parameters[3]] <= test1[3] #[MemBank.scala 56:28]
Firrtl cannot confirm that r_parameters has exhaustively connected test0.
One important question is do you need to need to have r_parameters be a Vec instead of just a Seq. If you change the r_parameters above to
val r_parameters = Seq(0, 3, 2, 1)
The Module will compile correctly. I suspect this is what you want. If you really need to r_parameters to be a dynamic index and you need to refactor your code. It is possible to add
test0 := DontCare
In front of your loop but I wouldn't recommend it in this case.
Hope this helps, happy chiseling!

Related

suggestName for IO(Vec(...))

I have a module like so...
class ApbSplitter (clients : List[ApbRange]) extends MultiIOModule {
val nApb = clients.length
val apb = IO(Vec(nApb, new ApbChannel()))
val apb_m = IO(Flipped(new ApbChannel))
...
What I'd like to do is suggestName to each element of the Vec so that instead of prefixed as apb_0_ apb_1_ etc... it's whatever I provide for each element.
I can apb.suggestName but that only affects the leading prefix and the array indices remain. Doing apb(idx).suggestName("blah") compiles but has no effect.
Any way to make this happen?
Got this to work by eliminating the Vec and creating a list of IO
case class ApbRange (name: String, loAddr : Int, hiAddr : Int)
class ApbSplitter (clients : List[ApbRange]) extends MultiIOModule {
val apb = clients.map({x => IO(new ApbChannel).suggestName(x.name)})
val apb_m = IO(Flipped(new ApbChannel))
...
Not sure if this is canonical but seems to do the trick just fine.
Answering this with Brian's other post and comment on his own answer on this post in mind. This is going to be a long answer because it touches on a couple of warts in the Chisel API that are being improved but are certainly relevant in the current version (v3.4.3 as of 12 Aug 2021).
Brian's answer is correct that if you want to name the individual fields you need to use a Seq and not a Vec. The reason for this is that, from Chisel's perspective, an IO of type Vec is a single port with an aggregate type, whereas the Seq is just a sequence of unrelated ports. The Seq is a Scala construct (whereas Vec comes from Chisel), so Chisel itself doesn't know anything about the relationship between the ports in the Seq.
The problem then, is that you need a Vec to do dynamic indexing. You can use VecInit to create a dynamically indexable Wire from your Seq whenever you need to do dynamic indexing:
For example:
class MyModule(names: Seq[String]) extends RawModule {
val enq = names.map(n => IO(Flipped(Decoupled(UInt(8.W)))).suggestName(n))
val idx = IO(Input(UInt(log2Ceil(names.size).W)))
val deq = IO(Decoupled(UInt(8.W)))
// enqWire connects all fields of enq
val enqWire = VecInit(enq)
// Need to make sure backpressure is always driven
enqWire.foreach(_.ready := false.B)
deq <> enqWire(idx)
}
This will work so long as deq is itself a port. It will not work if deq were a Wire because <> is a commutative operator and is thus ambiguous when connecting 2 bidirectional wires. For a longer explanation, see this PR comment.
If deq needs to be a Wire for some reason, you could use a helper module that does have Vecs as ports:
For example:
class InnerHelper(n: Int) extends RawModule {
val enq = IO(Flipped(Vec(n, Decoupled(UInt(8.W)))))
val idx = IO(Input(UInt(log2Ceil(n).W)))
val jdx = IO(Input(UInt(log2Ceil(n).W)))
val deq = IO(Vec(n, Decoupled(UInt(8.W))))
// backpressure defaults
enq.foreach(_.ready := false.B)
deq.foreach { x =>
x.valid := false.B
x.bits := DontCare
}
deq(jdx) <> enq(idx)
}
class MyModule(names: Seq[String]) extends RawModule {
val enq = names.map(n => IO(Flipped(Decoupled(UInt(8.W)))).suggestName(n))
val idx = IO(Input(UInt(log2Ceil(names.size).W)))
val jdx = IO(Input(UInt(log2Ceil(names.size).W)))
val deq = names.map(n => IO(Decoupled(UInt(8.W))).suggestName(s"${n}_out"))
val helper = Module(new InnerHelper(names.size))
helper.enq <> enq
helper.idx := idx
helper.jdx := jdx
helper.deq <> deq
}
It's a bit of a pain, but it at least resolves the ambiguity. There are other utilities we could build--for example, instead of a custom InnerHelper for each case, we could make a utility method that creates a module so that the returned value of dynamically indexing a Seq is a port of a new submodule, but it's a bit tricky.
The good news is that a better way is coming--DataView in Chisel 3.5 should make it possible to view a Seq as a Vec (rather than having to use VecInit which creates a Wire) which makes it easier to avoid this Wire <> connect ambiguity issue. I also hope to either "fix" <> for Wires or perhaps provide a new operator that is not commutative :<>, but that is not yet being worked on.
I am guessing your new apbChannel has a bunch of Input Output signals or wires. So instead of apb(idx).suggestName if your apbChannel has a (say) val ip = Input(Bool()) you can do apb(idx).ip.suggestName("blah")

Is there an accepted way to get a Gray Code counter in Chisel?

I'm looking to write counters in Chisel3 that will be used to address subunits. If the counter matches some register in a subunit then the subunit fires, otherwise it doesn't.
I would much rather have the addresses cycle in Gray code than in binary. It's easy enough to write a binary counter in Chisel, but I see no provision for a Gray code counter.
I can write a new type akin to Uint and Sint, but I'm reluctant to reinvent it if it's already out there. Yet I don't see anything in the cookbook or other docs about Gray code. Github just turns up a Minecraft-oriented repo (because it matches "chisel") There is existing stuff for VHDL but I want to express this in Chisel.
So have I missed a resource that would provide a Gray counter in Chisel? Failing that, is building a new type akin to Uint a reasonable way to proceed?
I did a quick look around and didn't find anything quite like what you're looking for. The closest thing I could find was a simple Gray counter in rocket-chip (https://github.com/chipsalliance/rocket-chip/blob/29ce00180f2a69947546d6385a1da86cbc584376/src/main/scala/util/AsyncQueue.scala#L49) but it uses regular binary counting and then just returns a UInt in Gray code. It also doesn't take advantage of any Scala type safety.
I think this would be a reasonable thing to build, and if you want you could contribute it to https://github.com/freechipsproject/ip-contributions for increased visibility.
I think if you wanted a proper GrayCode type, it would be reasonable to create a custom type. Unfortunately, there is no way to extend Data for a Bits-like type (all of the types in that hierarchy are sealed), but you could create a custom Bundle that wraps a UInt and then implement your own set of operations, eg.
class GrayCode(private val w: Int) extends Bundle {
val value = UInt(w.W)
def +(that: GrayCode): GrayCode = ???
}
object GrayCode {
// Lets you write GrayCode(4.W)
// Width is defined in chisel3.internal.firrtl though which is awkward...
def apply(width: Width): GrayCode = ???
}
This is just a quick sketch. The DSP Tools library has examples of custom types for DSP: https://github.com/ucb-bar/dsptools
They tend to use Scala Typeclasses a lot which is a more advanced Scala feature. Just mentioning in case some of the syntax in their looks alien.
You might take a look at this link programmersought gray code fifo it seems like it may be relevant but I am not familiar with it otherwise.
As with Jack I'm not familiar with the math needed to actually increment values in Gray code, but something like the following code would convert Gray code to binary, add, then convert it back to Gray code. I'm not sure if the Vec() code below would work correctly but should make the idea clear.
import chisel3._
import chisel3.util._
class GrayCode(private val w: Int) extends Bundle {
val value = UInt(w.W)
def bin2grey(x : UInt) : UInt = {
x ^ (x >> 1.U)
}
def grey2bin(x : UInt, n : Int) : UInt = {
val tmp = Wire(Vec(n, Bool()))
tmp(n-1) := x(n-1)
for (i <- 0 to (n-2)) {
tmp(i) := x(i) ^ tmp(i+1)
}
Cat(tmp.reverse)
}
def +(that: GrayCode): GrayCode = {
val sum = new GrayCode(w)
sum.value := grey2bin(bin2grey(this.value) + bin2grey(that.value), w)
sum
}
}
It seems like all implementations here use binary-to-Gray conversion. For asynchronous FIFOs, this only works if the Gray code is latched just before crossing clock domains. What if you want a counter that actually counts Gray codes instead of converting binary values to Gray codes?
One option is to convert Gray to binary, add, then convert back to Gray and store the result. The other is to use custom arithmetic to calculate the next Gray value in the sequence. The typical sequence is a reflected-binary Gray code, but others exist.
The code below implements a Gray code counter using a reflected-binary Gray code. It was adapted from this blog post. It only counts up. It works like the Chisel Counter object, except it adds support for a synchronous reset and custom register name. It returns the counter and wrap status.
import chisel3._
import chisel3.util._
// a Gray counter counts in Gray code
object GrayCounter {
// Gray unit cell
// b is the current state of this bit
// returns (t, z_o) where t is the next state of this bit
def grayCell(b: Bool, q_i: Bool, z_i: Bool, enable: Bool, parity: Bool): (Bool, Bool) = {
(b ^ (enable && q_i && z_i && parity), (!q_i) && z_i)
}
// cond = counts when true
// n = count value, must be a power of 2
// synchronousReset = resets counter to 0
// name = name for this counter
def apply(cond: Bool, n: Int, synchronousReset: Bool = false.B, name: String = null) = {
require(isPow2(n), s"Gray counter must have power-of-2 length (you asked for $n)")
require(n > 2, s"Gray counter minimum count is 4 (you asked for $n)")
val counter = RegInit(0.U(log2Ceil(n).W))
if (name != null) {
counter.suggestName(name)
}
val counterNext = Wire(Vec(log2Ceil(n), Bool()))
counter := counterNext.asUInt
val z_wires = Wire(Vec(log2Ceil(n), Bool()))
val parity = counter.xorR
for (i <- 0 until log2Ceil(n)) {
if (i == 0) {
val grayCellOut = grayCell(counter(i), true.B, true.B, cond, !parity)
counterNext(i) := grayCellOut._1
z_wires(i) := grayCellOut._2
} else {
val grayCellOut = grayCell(counter(i), counter(i-1) || (i == log2Ceil(n)-1).B,
z_wires(i-1) || (i == 1).B, cond, parity)
counterNext(i) := grayCellOut._1
z_wires(i) := grayCellOut._2
}
}
when (synchronousReset) {
counter := 0.U
}
val wrap = counter === (n/2).U && cond
(counter, wrap)
}
}

Error while passing values using peekpoketester

I am trying to pass some random integers (which I have stored in an array) to my hardware as an Input through the poke method in peekpoketester. But I am getting this error:
chisel3.internal.ChiselException: Error: Not in a UserModule. Likely cause: Missed Module() wrap, bare chisel API call, or attempting to construct hardware inside a BlackBox.
What could be the reason? I don't think I need a module wrap here as this is not hardware.
class TesterSimple (dut: DeviceUnderTest)(parameter1 : Int)(parameter2 : Int) extends
PeekPokeTester (dut) {
var x = Array[Int](parameter1)
var y = Array[Int](parameter2)
var z = 1
poke(dut.io.IP1, z.asUInt)
for(i <- 0 until parameter1){poke(dut.io.IP2(i), x(i).asUInt)}
for(j <- 0 until parameter2){poke(dut.io.IP3(j), y(j).asUInt)}
}
object TesterSimple extends App {
implicit val parameter1 = 2
implicit val parameter2 = 2
chisel3.iotesters.Driver (() => DeviceUnderTest(parameter1 :Int, parameter2 :Int)) { c =>
new TesterSimple (c)(parameter1, parameter2)}
}
I'd suggest a couple of things.
Main problem, I think you are not initializing your arrays properly
Try using Array.fill or Array.tabulate to create and initialize arrays
val rand = scala.util.Random
var x = Array.fill(parameter1)(rand.nextInt(100))
var y = Array.fill(parameter2)(rand.nextInt(100))
You don't need the .asUInt in the poke, it accepts Ints or BigInts
When defining hardware constants, use .U instead of .asUInt, the latter is a way of casting other chisel types, it does work but it a backward compatibility thing.
It's better to not start variables or methods with capital letters
I suggest us class DutName(val parameter1: Int, val parameter2: Int) or class DutName(val parameter1: Int)(val parameter2: Int) if you prefer.
This will allow to use the dut's paremeters when you are writing your test.
E.g. for(i <- 0 until dut.parameter1){poke(dut.io.IP2(i), x(i))}
This will save you have to duplicate parameter objects on your DUT and your Tester
Good luck!
Could you also share your DUT?
I believe the most likely case is your DUT does not extend Module

chisel hdl vector range assignment

I am new to Chisel HDL. I have a question regarding to Vec assignment. Suppose I have a Vec has n elements, and each one has w-bit SInt,
How can I assign a range of elements, let's say I have two Vec: a = Vec(10, SInt(width=8)), I have b = Vec(3, SInt(width=8)), How can I assign b := a(2:4)?
I know I can do it in for loop, is there any more elegant way to do it? I haven't find any example code or materials on it
Seems you are looking for a slice function in Vec. Glancing through
the Vec class I could not find such a function.
So the short answer is no, there is no elegant way to do this out-of-the-box.
The second most elegant thing is then to put such a function
in your project's util library and try to eventually
get this function upstreamed.
Implementing it in Chisel3 might look something like this:
class FooTester extends BasicTester {
def slice[T <: Data](someVec: Vec[T], startIndex: Int, endIndex: Int) : Vec[T] = {
Vec( for (i <- startIndex to endIndex) yield someVec(i) )
}
// An initialized Vec
val a = Vec(
Range(0, 10)
.map(SInt(_, width=8))
)
// A declared Vec
val b = Wire(Vec(3, SInt(width=8)))
b := slice(a, 2, 4)
assert(b(1) === SInt(3, width=8))
when(Counter(10).inc()) {stop()}
}
for (i <- 3 to 8) { my_vec(i) := something_at_index(i) }

Scala: Self-Recursive val in function [duplicate]

Why can't i define a variable recursively in a code block?
scala> {
| val test: Stream[Int] = 1 #:: test
| }
<console>:9: error: forward reference extends over definition of value test
val test: Stream[Int] = 1 #:: test
^
scala> val test: Stream[Int] = 1 #:: test
test: Stream[Int] = Stream(1, ?)
lazy keyword solves this problem, but i can't understand why it works without a code block but throws a compilation error in a code block.
Note that in the REPL
scala> val something = "a value"
is evaluated more or less as follows:
object REPL$1 {
val something = "a value"
}
import REPL$1._
So, any val(or def, etc) is a member of an internal REPL helper object.
Now the point is that classes (and objects) allow forward references on their members:
object ForwardTest {
def x = y // val x would also compile but with a more confusing result
val y = 2
}
ForwardTest.x == 2
This is not true for vals inside a block. In a block everything must be defined in linear order. Thus vals are no members anymore but plain variables (or values, resp.). The following does not compile either:
def plainMethod = { // could as well be a simple block
def x = y
val y = 2
x
}
<console>: error: forward reference extends over definition of value y
def x = y
^
It is not recursion which makes the difference. The difference is that classes and objects allow forward references, whereas blocks do not.
I'll add that when you write:
object O {
val x = y
val y = 0
}
You are actually writing this:
object O {
val x = this.y
val y = 0
}
That little this is what is missing when you declare this stuff inside a definition.
The reason for this behavior depends on different val initialization times. If you type val x = 5 directly to the REPL, x becomes a member of an object, which values can be initialized with a default value (null, 0, 0.0, false). In contrast, values in a block can not initialized by default values.
This tends to different behavior:
scala> class X { val x = y+1; val y = 10 }
defined class X
scala> (new X).x
res17: Int = 1
scala> { val x = y+1; val y = 10; x } // compiles only with 2.9.0
res20: Int = 11
In Scala 2.10 the last example does not compile anymore. In 2.9.0 the values are reordered by the compiler to get it to compile. There is a bug report which describes the different initialization times.
I'd like to add that a Scala Worksheet in the Eclipse-based Scala-IDE (v4.0.0) does not behave like the REPL as one might expect (e.g. https://github.com/scala-ide/scala-worksheet/wiki/Getting-Started says "Worksheets are like a REPL session on steroids") in this respect, but rather like the definition of one long method: That is, forward referencing val definitions (including recursive val definitions) in a worksheet must be made members of some object or class.