Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More Circt intrinsic wrappers (IsX, PlusArgsTest, PlusArgsValue) #2958

Merged
merged 23 commits into from
Apr 8, 2023
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/main/scala/chisel3/util/circt/IsX.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: Apache-2.0

package chisel3.util.circt

import chisel3._
import chisel3.experimental.IntrinsicModule
import chisel3.internal.Builder

import circt.Intrinsic

/** Create a module with a parameterized type which returns whether the input
* is a verilog 'x'.
*/
private class IsXIntrinsic[T <: Data](gen: T) extends IntrinsicModule("circt.isX") {
val i = IO(Input(gen))
val found = IO(Output(UInt(1.W)))
}

object IsX {

/** Creates an intrinsic which returns whether the input is a verilog 'x'.
*
* @example {{{
* b := IsX(a)
* }}}
*/
def apply[T <: Data](gen: T): Data = {
val inst = Module(new IsXIntrinsic(chiselTypeOf(gen)))
inst.i := gen
inst.found
}
}
37 changes: 37 additions & 0 deletions src/main/scala/chisel3/util/circt/PlusArgsTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: Apache-2.0

package chisel3.util.circt

import chisel3._
import chisel3.experimental.IntrinsicModule
import chisel3.internal.Builder

import circt.Intrinsic

/** Create a module with a parameterized type which calls the verilog function
* \$test\$plusargs to test for the existence of the string str in the
* simulator command line.
*/
private class PlusArgsTestIntrinsic[T <: Data](gen: T, str: String)
extends IntrinsicModule("circt.plusargs.test", Map("FORMAT" -> str)) {
val found = IO(Output(UInt(1.W)))
}

object PlusArgsTest {

/** Creates an intrinsic which calls \$test\$plusargs.
*
* @example {{{
* b := PlusArgsTest(UInt<32.W>, "FOO")
* }}}
*/
def apply[T <: Data](gen: T, str: String): Data = {
if (gen.isSynthesizable) {
val inst = Module(new PlusArgsTestIntrinsic(chiselTypeOf(gen), str))
inst.found
} else {
val inst = Module(new PlusArgsTestIntrinsic(gen, str))
inst.found
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code nit. It would likely be cleaner to do the maybe synthesizable unboxing explicitly to share some code:

Suggested change
if (gen.isSynthesizable) {
val inst = Module(new PlusArgsTestIntrinsic(chiselTypeOf(gen), str))
inst.found
} else {
val inst = Module(new PlusArgsTestIntrinsic(gen, str))
inst.found
}
val _gen = if (gen.isSynthesizable) {
chiselTypeOf(gen)
} else {
gen
}
val inst = Module(new PlusArgsTestIntrinsic(_gen, str))
inst.found

Alternatively, it would probably be better to have this require a Chisel type and not accept either a Chisel or Hardware type. Ditto for other intrinsics.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah we've generally leaned towards making it the user's problem to pass the right thing in (type vs hw)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seemed nicer to be able to pass in the kind of thing you are storing the result in rather than having to get it's type yourself. That way you can do a:

Wire w : UInt<4>
w <= PlusArgsTest(w, "FOO")

Copy link
Contributor

@mwachs5 mwachs5 Apr 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'd say a more common pattern would be val w = PlusArgsTest(UInt(4.W), "Foo")) (making wires is uncommon).

should we wrap a Default value in this API, if the plus args is not set?

}
}
42 changes: 42 additions & 0 deletions src/main/scala/chisel3/util/circt/PlusArgsValue.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: Apache-2.0

package chisel3.util.circt

import chisel3._
import chisel3.experimental.{FlatIO, IntrinsicModule}
import chisel3.internal.Builder

import circt.Intrinsic

/** Create a module which generates a verilog \$plusargs\$value. This returns a
* value as indicated by the format string and a flag for whether the value
* was found.
*/
private class PlusArgsValueIntrinsic[T <: Data](gen: T, str: String)
extends IntrinsicModule("circt.plusargs.value", Map("FORMAT" -> str)) {
val io = FlatIO(new Bundle {
val found = Output(UInt(1.W))
val result = Output(gen)
})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can directly use val found = Output(UInt(1.W)) instead of passing this through FlatIO. That really only becomes necessary when dealing with a BlackBox which dynamically checks that there is a val io.

Same nit as above, Bool is likely better for found.

For result, is this appropriate to take a type parameter? It seems like we wouldn't know what to do with this if it was anything other than a UInt? Would this be better expressed as a UInt of fixed width (for now) or parametric width (later)?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think @seldridge meant val found = IO(Output(Bool()) (edit mine on the Bool, but the point is you do still need the IO, but you're allowed to have as many IO calls as you want.

Copy link
Contributor

@mwachs5 mwachs5 Apr 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and we could still take a gen: UInt (no type paramterization) letting the user controls the width. Alternatively the old plus arg reader just forced you to specify the width and then it made the UInt with that width, no gen.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FlatIO was an old artifact of extmodule. Fixed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I take that back, this gives me a bundle for scala purposes but flat io in the module.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I care about exposing verilog functionality via an intrinsic, not about doing exactly what one code bases blackbox does.

}

object PlusArgsValue {

/** Creates an intrinsic which calls \$test\$plusargs.
*
* @example {{{
* b := PlusArgsValue(UInt(32.W), "FOO=%d")
* b.found
* b.value
* }}}
*/
def apply[T <: Data](gen: T, str: String) = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so is the intrinsic handling the unpacking into some complicated data type from the %d which is going to just be an integer? Is this useful vs making that happen explicitly in chisel and make this intrinsic just return a UInt?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intrinsic returns any verilog type which can be parsed with format strings (and is supported from firrtl). The format string can be used in verilog to pick apart complex specification strings for subfields you are interested in.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intrinsic is nothing more than a wrapper for verilog-spec functionality.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right, I am echoing Schuyler's comment above that I'm unclear why this can return anything other than a UInt at this level. Users can easily cast from UInt to their appropriate data type in a safer way than this happening automatically?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intrinsic isn't doing this, verilog is. What is safer in moving the casting point? It moves unsafe type conversion further into the user code.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that I understand that this is meaningful in verilog, I am OK with it. We might want to add something to the scaladoc that in terms of order / unpacking it's equivalent to using a UInt and then .asTypeOf(gen).

if (gen.isSynthesizable) {
val inst = Module(new PlusArgsValueIntrinsic(chiselTypeOf(gen), str))
inst.io
} else {
val inst = Module(new PlusArgsValueIntrinsic(gen, str))
inst.io
}
}
}
32 changes: 6 additions & 26 deletions src/main/scala/chisel3/util/circt/SizeOf.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,17 @@

package chisel3.util.circt

import scala.util.hashing.MurmurHash3

import chisel3._
import chisel3.experimental.{annotate, ChiselAnnotation, ExtModule}
import chisel3.experimental.IntrinsicModule
import chisel3.internal.{Builder, BuilderContextCache}

import circt.Intrinsic

// We have to unique designedName per type, be we can't due to name conflicts
// on bundles. Thus we use a globally unique id.
private object SizeOfGlobalIDGen {
private case object CacheKey extends BuilderContextCache.Key[Int]
def getID() = {
val oldID = Builder.contextCache.getOrElse(CacheKey, 0)
Builder.contextCache.put(CacheKey, oldID + 1)
oldID
}
}

/** Create a module with a parameterized type which returns the size of the type
* as a compile-time constant. This lets you write code which depends on the
* results of type inference.
*/
private class SizeOfIntrinsic[T <: Data](gen: T) extends ExtModule {
val i = IO(Input(gen));
private class SizeOfIntrinsic[T <: Data](gen: T) extends IntrinsicModule("circt.sizeof") {
val i = IO(Input(gen))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Way cleaner than the explicit annotation. 👍

val size = IO(Output(UInt(32.W)))
annotate(new ChiselAnnotation {
override def toFirrtl =
Intrinsic(toTarget, "circt.sizeof")
})
override val desiredName = "SizeOf_" + SizeOfGlobalIDGen.getID()
}

object SizeOf {
Expand All @@ -47,8 +27,8 @@ object SizeOf {
* }}}
*/
def apply[T <: Data](gen: T): Data = {
val sizeOfInst = Module(new SizeOfIntrinsic(chiselTypeOf(gen)))
sizeOfInst.i := gen
sizeOfInst.size
val inst = Module(new SizeOfIntrinsic(chiselTypeOf(gen)))
inst.i := gen
inst.size
}
}
49 changes: 49 additions & 0 deletions src/test/scala/chiselTests/util/IsXSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: Apache-2.0

package chiselTests.util

import chisel3._
import chisel3.stage.ChiselGeneratorAnnotation
import chisel3.testers.BasicTester
import chisel3.util.circt.IsX
import circt.stage.ChiselStage

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.io.Source

private class IsXBundle extends Bundle {
val a = UInt()
val b = SInt()
}

private class IsXTop extends Module {
val io = IO(new Bundle {
val w = Input(UInt(65.W))
val x = Input(new IsXBundle)
val y = Input(UInt(65.W))
val outw = UInt(1.W)
val outx = UInt(1.W)
val outy = UInt(1.W)
})
io.outw := IsX(io.w)
io.outx := IsX(io.x)
io.outy := IsX(io.y)
}

class IsXSpec extends AnyFlatSpec with Matchers {
it should "Should work for types" in {
val fir = ChiselStage.emitCHIRRTL(new IsXTop)
println(fir)
(
(fir.split('\n').map(x => x.trim) should contain).allOf(
"intmodule IsXIntrinsic :",
"input i : UInt<65>",
"output found : UInt<1>",
"intrinsic = circt.isX",
"input i : { a : UInt, b : SInt}"
)
)
}
}
37 changes: 37 additions & 0 deletions src/test/scala/chiselTests/util/PlusArgsTestSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: Apache-2.0

package chiselTests.util

import chisel3._
import chisel3.testers.BasicTester
import chisel3.util.circt.PlusArgsTest
import circt.stage.ChiselStage

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.io.Source

private class PlusArgsTestTop extends Module {
val io = IO(new Bundle {
val w = Output(UInt(1.W))
val x = Output(UInt(1.W))
val z = Input(UInt(32.W))
})
io.w := PlusArgsTest(UInt(32.W), "FOO")
io.x := PlusArgsTest(io.z, "BAR")
}

class PlusArgsTestSpec extends AnyFlatSpec with Matchers {
it should "Should work for types" in {
val fir = ChiselStage.emitCHIRRTL(new PlusArgsTestTop)
println(fir)
(fir.split('\n').map(x => x.trim) should contain).allOf(
"intmodule PlusArgsTestIntrinsic :",
"output found : UInt<1>",
"intrinsic = circt.plusargs.test",
"parameter FORMAT = \"FOO\"",
"parameter FORMAT = \"BAR\""
)
}
}
41 changes: 41 additions & 0 deletions src/test/scala/chiselTests/util/PlusArgsValueSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: Apache-2.0

package chiselTests.util

import chisel3._
import chisel3.testers.BasicTester
import chisel3.util.circt.PlusArgsValue
import circt.stage.ChiselStage

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.io.Source

private class PlusArgsValueTop extends Module {
val io = IO(new Bundle {
val wf = Output(UInt(1.W))
val wv = Output(UInt(32.W))
val xf = Output(UInt(1.W))
val xv = Output(UInt(32.W))
})
val tmpw = PlusArgsValue(UInt(32.W), "FOO=%d")
val tmpx = PlusArgsValue(io.xv, "BAR=%d")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we are going to support complicated bundle types then please show a test of that here... but I'm not sure the advantage of having it take any Data vs just a UInt (or SInt possibly through some API...?)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here, for example is parsing a non-integer substring. We can't express this in firrtl since we don't have real types, but in verilog: $value$plusargs("FREQ+%0F",frequency)

you can also control integer encoding in parsing, parse strings, etc.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you show that being used in the test?

how would we cast something with format string "FREQ+%0F" to a gen: DecoupledIO(UInt(32.W)), something the API will happily let us do right now?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Example with a struct: #2958 (comment)

Copy link
Contributor

@mwachs5 mwachs5 Apr 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and if the format string is user controlled please show some tests/applications of things that are not of the form "SomeSTring=%d"

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To what end? The string is passed by chisel verbatim to firrtl. These are not end-to-end verilog generation tests.

Copy link
Contributor

@mwachs5 mwachs5 Apr 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a user API we are designing. I am trying to understand the utility of exposing this string to the user, as well as the utility of allowing arbitrary gen data types. If we have no use for it, and users are only ever going to reasonably get UInts back, then let's remove the ambiguity int he API. If we are saying "sure, you can format your plusarg as a float, or signed number" then what do we expect the users to assign those to?

Why isn't the utility something like PlusArgValueUInt, PlusArgValueSInt.

I'm not even sure what we'd do with a PlusArgValueFloat

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we are trying to formalize https://github.com/chipsalliance/rocket-chip/blob/master/src/main/resources/vsrc/plusarg_reader.v, which does expose the format string, but not the output data type (which is hard-coded to a UInt of a user-specified width).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are not trying to formalize that. We are trying to provide access to functionality described in SV 2012 section 21.6. That that blackbox will be directly implementable is a (intended) side effect.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A missing point is it is not the case that the format has to be "STR=FORMAT", it can be any pattern match.

io.xf := tmpx.found
io.xv := tmpx.result
}

class PlusArgsValueSpec extends AnyFlatSpec with Matchers {
it should "Should work for types" in {
val fir = ChiselStage.emitCHIRRTL(new PlusArgsValueTop)
println(fir)
(fir.split('\n').map(x => x.trim) should contain).inOrder(
"intmodule PlusArgsValueIntrinsic :",
"output found : UInt<1>",
"output result : UInt<32>",
"intrinsic = circt.plusargs.value",
"parameter FORMAT = \"FOO=%d\"",
"parameter FORMAT = \"BAR=%d\""
)
}
}
42 changes: 8 additions & 34 deletions src/test/scala/chiselTests/util/SizeOfSpec.scala
Original file line number Diff line number Diff line change
@@ -1,64 +1,38 @@
// SPDX-License-Identifier: Apache-2.0

package chiselTests.util

import chisel3._
import chisel3.stage.ChiselGeneratorAnnotation
import chisel3.testers.BasicTester
import chisel3.util.circt.SizeOf

import circt.stage.ChiselStage

import firrtl.stage.FirrtlCircuitAnnotation

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import scala.io.Source

class MyBundle extends Bundle {
private class SizeOfBundle extends Bundle {
val a = UInt()
val b = SInt()
}

class SizeOfTop extends Module {
private class SizeOfTop extends Module {
val io = IO(new Bundle {
val w = Input(UInt(65.W))
val x = Input(new MyBundle)
val x = Input(new SizeOfBundle)
val outw = UInt(32.W)
val outx = UInt(32.W)
})
io.outw := SizeOf(io.w)
io.outx := SizeOf(io.x)
}

/** A test for intrinsics. Since chisel is producing intrinsics as tagged
* extmodules (for now), we explicitly test the chirrtl and annotations rather
* than the processed firrtl or verilog. It is worth noting that annotations
* are implemented (for now) in a way which makes the output valid for all
* firrtl compilers, hence we write a localized, not end-to-end test
*/
class SizeOfSpec extends AnyFlatSpec with Matchers {
it should "Should work for types" in {
val fir = ChiselStage.emitCHIRRTL(new SizeOfTop)
val a1 = """extmodule SizeOf_0""".r
(fir should include).regex(a1)
val b1 = """defname = SizeOf_0""".r
(fir should include).regex(b1)
val a2 = """extmodule SizeOf_1""".r
(fir should include).regex(a2)
val b2 = """defname = SizeOf_1""".r
(fir should include).regex(b2)

// The second elaboration uses a unique name since the Builder is reused (?)
val c = """Intrinsic\(~SizeOfTop\|SizeOf.*,circt.sizeof\)"""
((new ChiselStage)
.execute(
args = Array("--target", "chirrtl"),
annotations = Seq(chisel3.stage.ChiselGeneratorAnnotation(() => new SizeOfTop))
)
.flatMap {
case FirrtlCircuitAnnotation(circuit) => circuit.annotations
case _ => None
}
.mkString("\n") should include).regex(c)
println(fir)
(fir.split('\n').map(x => x.trim) should contain)
.allOf("intmodule SizeOfIntrinsic :", "input i : UInt<65>", "output size : UInt<32>", "intrinsic = circt.sizeof")
}
}