Path: blob/21.2-virgl/src/util/fast_urem_by_const.h
4545 views
/*1* Copyright © 2010 Valve Software2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice (including the next11* paragraph) shall be included in all copies or substantial portions of the12* Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL17* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING19* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS20* IN THE SOFTWARE.21*/2223#include <stdint.h>2425/*26* Code for fast 32-bit unsigned remainder, based off of "Faster Remainder by27* Direct Computation: Applications to Compilers and Software Libraries,"28* available at https://arxiv.org/pdf/1902.01961.pdf.29*30* util_fast_urem32(n, d, REMAINDER_MAGIC(d)) returns the same thing as31* n % d for any unsigned n and d, however it compiles down to only a few32* multiplications, so it should be faster than plain uint32_t modulo if the33* same divisor is used many times.34*/3536#define REMAINDER_MAGIC(divisor) \37((uint64_t) ~0ull / (divisor) + 1)3839/*40* Get bits 64-96 of a 32x64-bit multiply. If __int128_t is available, we use41* it, which usually compiles down to one instruction on 64-bit architectures.42* Otherwise on 32-bit architectures we usually get four instructions (one43* 32x32->64 multiply, one 32x32->32 multiply, and one 64-bit add).44*/4546static inline uint32_t47_mul32by64_hi(uint32_t a, uint64_t b)48{49#ifdef HAVE_UINT12850return ((__uint128_t) b * a) >> 64;51#else52/*53* Let b = b0 + 2^32 * b1. Then a * b = a * b0 + 2^32 * a * b1. We would54* have to do a 96-bit addition to get the full result, except that only55* one term has non-zero lower 32 bits, which means that to get the high 3256* bits, we only have to add the high 64 bits of each term. Unfortunately,57* we have to do the 64-bit addition in case the low 32 bits overflow.58*/59uint32_t b0 = (uint32_t) b;60uint32_t b1 = b >> 32;61return ((((uint64_t) a * b0) >> 32) + (uint64_t) a * b1) >> 32;62#endif63}6465static inline uint32_t66util_fast_urem32(uint32_t n, uint32_t d, uint64_t magic)67{68uint64_t lowbits = magic * n;69uint32_t result = _mul32by64_hi(d, lowbits);70assert(result == n % d);71return result;72}73747576