From ae784b6e9dde1a5692b37067573cfddc164cdf26 Mon Sep 17 00:00:00 2001 From: Jim Lawson Date: Thu, 18 Jul 2019 13:46:53 -0700 Subject: 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. --- src/main/scala/chisel3/util/Math.scala | 36 ++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) (limited to 'src/main') 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 + } + + } +} -- cgit v1.2.3