Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion core/src/main/scala/chisel3/internal/firrtl/IR.scala
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,9 @@ private[chisel3] object ir {
val unsigned = if (n < 0) (BigInt(1) << width.get) + n else n
s"asSInt(${ULit(unsigned, width).name})"
}
def minWidth: Int = (if (w.known) 0 else 1) + n.bitLength

// Special case for 0 which can be specified to zero-width (but defaults to 1 bit).
def minWidth: Int = if (n == 0 && w.known) 0 else 1 + n.bitLength

def cloneWithWidth(newWidth: Width): this.type = {
SLit(n, newWidth).asInstanceOf[this.type]
Expand Down
14 changes: 14 additions & 0 deletions src/test/scala-2/chiselTests/SIntOps.scala
Original file line number Diff line number Diff line change
Expand Up @@ -284,4 +284,18 @@ class SIntOpsSpec extends AnyPropSpec with Matchers with ShiftRightWidthBehavior
blit.x.litOption should be(Some(2))
blit.y.litOption should be(Some(9))
}

property("SInt literals with too small of a width should be rejected") {
// Sanity checks.
0.S.getWidth should be(1)
0.S(0.W).getWidth should be(0)
-1.S.getWidth should be(1)
1.S.getWidth should be(2)
// The real check.
-2.S.getWidth should be(2)
an[IllegalArgumentException] shouldBe thrownBy(-2.S(1.W))
0xde.S.getWidth should be(9)
an[IllegalArgumentException] shouldBe thrownBy(0xde.S(8.W))
an[IllegalArgumentException] shouldBe thrownBy(0xde.S(4.W))
}
Comment on lines +288 to +300
Copy link
Member

Choose a reason for hiding this comment

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

These tests look right! I haven't thought through the other ramifications of this change, other than that the existing tests in the repo all pass.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah I'm confident it's correct. Note that even before this change 0xde.S.getWidth == 9, it's just that we were accepting 1-bit less than the correct answer if the user specified it which would then coincidentally do the right thing in most circumstances due to the FIRRTL we emitted actually having the correct width semantics. Thus things would work as long as you didn't introspect on the width and do things with it.

}