Creating Modules in chisel dynamically and at the same time passing dynamic parameters to those modules

Viewed 297

Consider this example

for(x <- 0 until numberOfHWBlocks){
    val hw_block = Module(new HW_BLOCK(x)(p :Parameters)).io
}

Each time this creates a new module according to whatever x is. What I want is that I do not want to declare val hw_block each time as a separate entity inside the for loop as this value overrides the previous value. I want a seq of these modules stored in a single val. Something like this

for( x <- 0 until numberOfHWBlocks){
    hw_block(x) = Module(new HW_BLOCK(x)(p :Parameters)).io
}

where hw_block is defined as a Seq outside the for loop

val hw_block = Seq.fill(numberOfHWBlocks){//What do I have to instantiate here??//}
2 Answers

Have you considered tabulate

val hw_block = Seq.tablulate(numberOfHardHWBlocks) { x =>
  Module(new HW_BLOCK(x)(p :Parameters)).io
}

tabulate is like file but gives you the ability to distinguish which element is being instantiated

Note: I think your syntax for the Module creation is slightly wrong. I think it should be Module(new HW_BLOCK(...)).io, this creates the module then returns the io bundle for reference in HW_Block

tabulate as in the comment and Chick's response is the best answer, but I'll provide a little more context because tabulate is kind of a special case for when you want to construct from a range of Integers starting from 0.

Say I had a Seq of Strings that I wanted to construct a Seq of Modules from, how would I do it? Many who are new to Chisel and Scala will think of a for loop and mutation. While in Scala we generally prefer to use immutable types and functional programming, you can still accomplish this with mutation:

val myModules = ArrayBuffer[MyModule]()
val myParams = Seq("foo", "bar")
for (param <- myStrings) {
  myModules += Module(new MyModule(param)) // .io if you just want the io ports
}

This is more akin to your original idea, so how can I make this more functional in a way similar to Seq.fill and Seq.tabulate? We can take the Seq of parameters we wish to pass, and map on it:

val myParams = Seq("foo", "bar")
val myModules = myParams.map(param => Module(new MyModule(param)))

As I said previously, Seq.tabulate is a special case of this more general map pattern where you have a range of integers, thus your case could alternatively be expressed as:

(0 until numberOfHWBlocks).map(x => Module(new HW_BLOCK(x)(p: Parameters).io))
Related