2 * Copyright (c) 2008 Joshua Phillips. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
15 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
16 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
19 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
21 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
23 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
25 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // return a/b rounded up
32 static inline unsigned long uldivru(unsigned long a
, unsigned long b
)
41 static inline unsigned long long ulldivru(unsigned long long a
, unsigned long long b
)
50 int log2ll(long long n
); // return base-2 log of n, rounded down
52 // return log base 2 of v
53 static inline unsigned int ilog2(unsigned int v
)
55 static const unsigned int b
[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000};
56 static const unsigned int S
[] = {1, 2, 4, 8, 16};
58 register unsigned int r
= 0; // result goes here
68 // return log base 2 of v, rounded up
69 static inline unsigned int ilog2up(unsigned int v
)
71 // do it the nasty way
72 unsigned int log
= ilog2(v
);
73 if (v
& ((1 << log
) - 1))
78 // return 'value' rounded up to nearest 'alignment' multiple
79 // hopefully, since these are inline, cc will optimize the division
80 // and modulus for shifts and ands.
81 static inline unsigned long alignup(unsigned long value
, unsigned long alignment
)
83 return uldivru(value
, alignment
) * alignment
;
86 // return 'value' rounded down to nearest 'alignment' multiple
87 static inline unsigned long aligndn(unsigned long value
, unsigned long alignment
)
89 return (value
/ alignment
) * alignment
;
92 static inline unsigned int bsf(unsigned int x
)
96 "bsfl %1,%0" : "=r" (result
) : "r" (x
));