Mesa (main): util: Use shifts in util_sign_extend

GitLab Mirror gitlab-mirror at kemper.freedesktop.org
Wed Jul 6 12:09:28 UTC 2022


Module: Mesa
Branch: main
Commit: 53eeb1e238d9b7ad3938e74075b3008593c2c1da
URL:    http://cgit.freedesktop.org/mesa/mesa/commit/?id=53eeb1e238d9b7ad3938e74075b3008593c2c1da

Author: Jason Ekstrand <jason.ekstrand at collabora.com>
Date:   Thu Jun 23 12:30:48 2022 -0500

util: Use shifts in util_sign_extend

As long as we left-shift the unsigned version, this has no undefined
behavior and is fewer instructions.  The only tricky bit is that a right
shift of a negative number is technically implementation-defined (not
undefined) behavior in C.  However, if it's ever anything other than an
arithmatic right-shift, there's lots of other places where Mesa will
break today.

Reviewed-by: Alyssa Rosenzweig <alyssa.rosenzweig at collabora.com>
Reviewed-by: Kristian H. Kristensen <hoegsberg at gmail.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/17214>

---

 src/util/u_math.h | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/src/util/u_math.h b/src/util/u_math.h
index 52f5c6d53a3..cf2e079cdcd 100644
--- a/src/util/u_math.h
+++ b/src/util/u_math.h
@@ -589,12 +589,9 @@ static inline int64_t
 util_sign_extend(uint64_t val, unsigned width)
 {
    assert(width > 0 && width <= 64);
-   assert(width == 64 || val < (1ull << width));
-   if (val & (UINT64_C(1) << (width - 1))) {
-      return -(int64_t)((UINT64_C(1) << width) - val);
-   } else {
-      return val;
-   }
+   assert(width == 64 || val < (UINT64_C(1) << width));
+   unsigned shift = 64 - width;
+   return (int64_t)(val << shift) >> shift;
 }
 
 static inline void*



More information about the mesa-commit mailing list