Re: [PATCH v2 10/19] host-utils: Introduce mulu128

2021-09-03 Thread Richard Henderson

On 8/31/21 6:39 PM, Luis Pires wrote:

+*phigh = ahi + blo;
+
+return (bhi > 0) || (*phigh < ahi);


return add64_overflow(ahi, blo, phigh) || bhi != 0

With that,
Reviewed-by: Richard Henderson 


r~



[PATCH v2 10/19] host-utils: Introduce mulu128

2021-08-31 Thread Luis Pires
Signed-off-by: Luis Pires 
---
 include/qemu/host-utils.h | 38 ++
 1 file changed, 38 insertions(+)

diff --git a/include/qemu/host-utils.h b/include/qemu/host-utils.h
index 6f18b29921..9f40077083 100644
--- a/include/qemu/host-utils.h
+++ b/include/qemu/host-utils.h
@@ -588,6 +588,44 @@ static inline bool umul64_overflow(uint64_t x, uint64_t y, 
uint64_t *ret)
 #endif
 }
 
+/*
+ * Unsigned 128x64 multiplication.
+ * Returns true if the result got truncated to 128 bits.
+ * Otherwise, returns false and the multiplication result via plow and phigh.
+ */
+static inline bool mulu128(uint64_t *plow, uint64_t *phigh, uint64_t factor)
+{
+#if defined(CONFIG_INT128) && \
+(__has_builtin(__builtin_mul_overflow) || __GNUC__ >= 5)
+bool res;
+__uint128_t r;
+__uint128_t f = ((__uint128_t)*phigh << 64) | *plow;
+res = __builtin_mul_overflow(f, factor, );
+
+*plow = r;
+*phigh = r >> 64;
+
+return res;
+#else
+uint64_t dhi = *phigh;
+uint64_t dlo = *plow;
+uint64_t ahi;
+uint64_t blo, bhi;
+
+if (dhi == 0) {
+mulu64(plow, phigh, dlo, factor);
+return false;
+}
+
+mulu64(plow, , dlo, factor);
+mulu64(, , dhi, factor);
+
+*phigh = ahi + blo;
+
+return (bhi > 0) || (*phigh < ahi);
+#endif
+}
+
 /**
  * uadd64_carry - addition with carry-in and carry-out
  * @x, @y: addends
-- 
2.25.1