Skip to content

Commit

Permalink
libutils: util.h: Relax ROUNDDOWN() and add ROUNDDOWN2()
Browse files Browse the repository at this point in the history
Remove constraint on ROUNDDOWN() to have its size argument being a power
of 2 and add new ROUNDDOWN2() macro with that constraint.

The previous implementation of ROUNDDOWN(), optimized for when size
argument is a power of 2, is now used for ROUNDDOWN2() but this latter
also asserts (in debug build mode) that the size argument conforms to
this condition.

The new implementation of ROUNDDOWN() is less optimal but modern
compilers produce the same optimized assembly code with this macro when
the size argument is a constant value known from the compiler so all
use of ROUNDDOWN() with a known constant value do not need move to
ROUNDDOWN2().

Performance sensitive routines should now on use ROUNDDOWN2() to
leverage the power-of-2 rounding optimization.

Signed-off-by: Etienne Carriere <[email protected]>
Reviewed-by: Jens Wiklander <[email protected]>
  • Loading branch information
etienne-lms authored and jforissier committed Dec 19, 2024
1 parent 8132f3b commit fa418fc
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/libutils/ext/include/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,15 @@
*/
#define ROUNDUP_DIV(x, y) (ROUNDUP((x), (y)) / (__typeof__(x))(y))

/* Round down the even multiple of size */
#define ROUNDDOWN(x, y) (((x) / (__typeof__(x))(y)) * (__typeof__(x))(y))

/* Round down the even multiple of size, size has to be a power of 2 */
#define ROUNDDOWN(v, size) ((v) & ~((__typeof__(v))(size) - 1))
#define ROUNDDOWN2(v, size) \
(__extension__({ \
assert(IS_POWER_OF_TWO(size)); \
((v) & ~((__typeof__(v))(size) - 1)); \
}))

/*
* Round up the result of x / y to the nearest upper integer if result is not
Expand Down

0 comments on commit fa418fc

Please sign in to comment.