summaryrefslogtreecommitdiff
path: root/src/main/scala
diff options
context:
space:
mode:
authorJim Lawson2019-07-18 13:46:53 -0700
committerGitHub2019-07-18 13:46:53 -0700
commitae784b6e9dde1a5692b37067573cfddc164cdf26 (patch)
treed53a68a4e3f71d5ceeda0c41f2e558d1530ce776 /src/main/scala
parent8b8586087c0c8370773b453fb28ac5d426909e38 (diff)
Add width utility functions to avoid incorrect usage of bare log2Ceil(). (#819)
* Add width utility functions to avoid incorrect usage of bare log2Ceil(). * Respond to comments: Remove apply(Data) method. Change name(s) to signedBitLength, unsignedBitLength. * Respond to comments - don't be lazy. Independently calculate the bit length to verify correct operation. * Respond to comments - return in.bitLength - 0 (not 1) for 0 * Respond to comments - update wdith for signed 0; add explicit tests. * Add comment expressing zero width wire assumption.
Diffstat (limited to 'src/main/scala')
-rw-r--r--src/main/scala/chisel3/util/Math.scala36
1 files changed, 34 insertions, 2 deletions
diff --git a/src/main/scala/chisel3/util/Math.scala b/src/main/scala/chisel3/util/Math.scala
index f9278c7d..105b4161 100644
--- a/src/main/scala/chisel3/util/Math.scala
+++ b/src/main/scala/chisel3/util/Math.scala
@@ -5,8 +5,7 @@
package chisel3.util
-import chisel3._
-import chisel3.internal.chiselRuntimeDeprecated
+import chisel3.internal
/** Compute the log2 of a Scala integer, rounded up, with min value of 1.
* Useful for getting the number of bits needed to represent some number of states (in - 1),
@@ -99,3 +98,36 @@ object isPow2 {
def apply(in: BigInt): Boolean = in > 0 && ((in & (in-1)) == 0)
def apply(in: Int): Boolean = apply(BigInt(in))
}
+
+
+object unsignedBitLength {
+ /** Return the number of bits required to encode a specific value, assuming no sign bit is required.
+ *
+ * Basically, `n.bitLength`. NOTE: This will return 0 for a value of 0.
+ * This reflects the Chisel assumption that a zero width wire has a value of 0.
+ * @param in - the number to be encoded.
+ * @return - an Int representing the number of bits to encode.
+ */
+ def apply(in: BigInt): Int = {
+ require(in >= 0)
+ in.bitLength
+ }
+}
+
+object signedBitLength {
+ /** Return the number of bits required to encode a specific value, assuming a sign bit is required.
+ *
+ * Basically, 0 for 0, 1 for -1, and `n.bitLength` + 1 for everything else.
+ * This reflects the Chisel assumption that a zero width wire has a value of 0.
+ * @param in - the number to be encoded.
+ * @return - an Int representing the number of bits to encode.
+ */
+ def apply(in: BigInt): Int = {
+ in.toInt match {
+ case 0 => 0
+ case -1 => 1
+ case _ => in.bitLength + 1
+ }
+
+ }
+}