1 /*
2  * libecb - http://software.schmorp.de/pkg/libecb
3  *
4  * Copyright (©) 2009-2011 Marc Alexander Lehmann <libecb@schmorp.de>
5  * Copyright (©) 2011 Emanuele Giaquinta
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without modifica-
9  * tion, are permitted provided that the following conditions are met:
10  *
11  *   1.  Redistributions of source code must retain the above copyright notice,
12  *       this list of conditions and the following disclaimer.
13  *
14  *   2.  Redistributions in binary form must reproduce the above copyright
15  *       notice, this list of conditions and the following disclaimer in the
16  *       documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
19  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
20  * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
21  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
22  * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
24  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
26  * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
27  * OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #ifndef ECB_H
31 #define ECB_H
32 
33 #ifdef _WIN32
34   typedef   signed char   int8_t;
35   typedef unsigned char  uint8_t;
36   typedef   signed short  int16_t;
37   typedef unsigned short uint16_t;
38   typedef   signed int    int32_t;
39   typedef unsigned int   uint32_t;
40   #if __GNUC__
41     typedef   signed long long int64_t;
42     typedef unsigned long long uint64_t;
43   #else /* _MSC_VER || __BORLANDC__ */
44     typedef   signed __int64   int64_t;
45     typedef unsigned __int64   uint64_t;
46   #endif
47 #else
48   #include <inttypes.h>
49 #endif
50 
51 /* many compilers define _GNUC_ to some versions but then only implement
52  * what their idiot authors think are the "more important" extensions,
53  * causing enormous grief in return for some better fake benchmark numbers.
54  * or so.
55  * we try to detect these and simply assume they are not gcc - if they have
56  * an issue with that they should have done it right in the first place.
57  */
58 #ifndef ECB_GCC_VERSION
59   #if !defined(__GNUC_MINOR__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) || defined(__llvm__) || defined(__clang__)
60     #define ECB_GCC_VERSION(major,minor) 0
61   #else
62     #define ECB_GCC_VERSION(major,minor) (__GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
63   #endif
64 #endif
65 
66 /*****************************************************************************/
67 
68 /* ECB_NO_THREADS - ecb is not used by multiple threads, ever */
69 /* ECB_NO_SMP     - ecb might be used in multiple threads, but only on a single cpu */
70 
71 #if ECB_NO_THREADS || ECB_NO_SMP
72   #define ECB_MEMORY_FENCE do { } while (0)
73 #endif
74 
75 #ifndef ECB_MEMORY_FENCE
76   #if ECB_GCC_VERSION(2,5) || defined(__INTEL_COMPILER) || defined(__clang__)
77     #if __i386__
78       #define ECB_MEMORY_FENCE         __asm__ __volatile__ ("lock; orb $0, -1(%%esp)" : : : "memory")
79       #define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE /* non-lock xchg might be enough */
80       #define ECB_MEMORY_FENCE_RELEASE do { } while (0) /* unlikely to change in future cpus */
81     #elif __amd64
82       #define ECB_MEMORY_FENCE         __asm__ __volatile__ ("mfence" : : : "memory")
83       #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("lfence" : : : "memory")
84       #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("sfence") /* play safe - not needed in any current cpu */
85     #elif __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__
86       #define ECB_MEMORY_FENCE         __asm__ __volatile__ ("sync" : : : "memory")
87     #elif defined(__ARM_ARCH_6__ ) || defined(__ARM_ARCH_6J__ ) \
88        || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6ZK__)
89       #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mcr p15,0,%0,c7,c10,5" : : "r" (0) : "memory")
90     #elif defined(__ARM_ARCH_7__ ) || defined(__ARM_ARCH_7A__ ) \
91        || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7R__ )
92       #define ECB_MEMORY_FENCE         __asm__ __volatile__ ("dmb" : : : "memory")
93     #endif
94   #endif
95 #endif
96 
97 #ifndef ECB_MEMORY_FENCE
98   #if ECB_GCC_VERSION(4,4) || defined(__INTEL_COMPILER) || defined(__clang__)
99     #define ECB_MEMORY_FENCE         __sync_synchronize ()
100     /*#define ECB_MEMORY_FENCE_ACQUIRE ({ char dummy = 0; __sync_lock_test_and_set (&dummy, 1); }) */
101     /*#define ECB_MEMORY_FENCE_RELEASE ({ char dummy = 1; __sync_lock_release      (&dummy   ); }) */
102   #elif _MSC_VER >= 1400 /* VC++ 2005 */
103     #pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier)
104     #define ECB_MEMORY_FENCE         _ReadWriteBarrier ()
105     #define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier () /* according to msdn, _ReadBarrier is not a load fence */
106     #define ECB_MEMORY_FENCE_RELEASE _WriteBarrier ()
107   #elif defined(_WIN32)
108     #include <WinNT.h>
109     #define ECB_MEMORY_FENCE         MemoryBarrier () /* actually just xchg on x86... scary */
110   #endif
111 #endif
112 
113 #ifndef ECB_MEMORY_FENCE
114   #if !ECB_AVOID_PTHREADS
115     /*
116      * if you get undefined symbol references to pthread_mutex_lock,
117      * or failure to find pthread.h, then you should implement
118      * the ECB_MEMORY_FENCE operations for your cpu/compiler
119      * OR provide pthread.h and link against the posix thread library
120      * of your system.
121      */
122     #include <pthread.h>
123     #define ECB_NEEDS_PTHREADS 1
124     #define ECB_MEMORY_FENCE_NEEDS_PTHREADS 1
125 
126     static pthread_mutex_t ecb_mf_lock = PTHREAD_MUTEX_INITIALIZER;
127     #define ECB_MEMORY_FENCE do { pthread_mutex_lock (&ecb_mf_lock); pthread_mutex_unlock (&ecb_mf_lock); } while (0)
128   #endif
129 #endif
130 
131 #if !defined(ECB_MEMORY_FENCE_ACQUIRE) && defined(ECB_MEMORY_FENCE)
132   #define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE
133 #endif
134 
135 #if !defined(ECB_MEMORY_FENCE_RELEASE) && defined(ECB_MEMORY_FENCE)
136   #define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE
137 #endif
138 
139 /*****************************************************************************/
140 
141 #define ECB_C99 (__STDC_VERSION__ >= 199901L)
142 
143 #if __cplusplus
144   #define ecb_inline static inline
145 #elif ECB_GCC_VERSION(2,5)
146   #define ecb_inline static __inline__
147 #elif ECB_C99
148   #define ecb_inline static inline
149 #else
150   #define ecb_inline static
151 #endif
152 
153 #if ECB_GCC_VERSION(3,3)
154   #define ecb_restrict __restrict__
155 #elif ECB_C99
156   #define ecb_restrict restrict
157 #else
158   #define ecb_restrict
159 #endif
160 
161 typedef int ecb_bool;
162 
163 #define ECB_CONCAT_(a, b) a ## b
164 #define ECB_CONCAT(a, b) ECB_CONCAT_(a, b)
165 #define ECB_STRINGIFY_(a) # a
166 #define ECB_STRINGIFY(a) ECB_STRINGIFY_(a)
167 
168 #define ecb_function_ ecb_inline
169 
170 #if ECB_GCC_VERSION(3,1)
171   #define ecb_attribute(attrlist)        __attribute__(attrlist)
172   #define ecb_is_constant(expr)          __builtin_constant_p (expr)
173   #define ecb_expect(expr,value)         __builtin_expect ((expr),(value))
174   #define ecb_prefetch(addr,rw,locality) __builtin_prefetch (addr, rw, locality)
175 #else
176   #define ecb_attribute(attrlist)
177   #define ecb_is_constant(expr)          0
178   #define ecb_expect(expr,value)         (expr)
179   #define ecb_prefetch(addr,rw,locality)
180 #endif
181 
182 /* no emulation for ecb_decltype */
183 #if ECB_GCC_VERSION(4,5)
184   #define ecb_decltype(x) __decltype(x)
185 #elif ECB_GCC_VERSION(3,0)
186   #define ecb_decltype(x) __typeof(x)
187 #endif
188 
189 #define ecb_noinline   ecb_attribute ((__noinline__))
190 #define ecb_noreturn   ecb_attribute ((__noreturn__))
191 #define ecb_unused     ecb_attribute ((__unused__))
192 #define ecb_const      ecb_attribute ((__const__))
193 #define ecb_pure       ecb_attribute ((__pure__))
194 
195 #if ECB_GCC_VERSION(4,3)
196   #define ecb_artificial ecb_attribute ((__artificial__))
197   #define ecb_hot        ecb_attribute ((__hot__))
198   #define ecb_cold       ecb_attribute ((__cold__))
199 #else
200   #define ecb_artificial
201   #define ecb_hot
202   #define ecb_cold
203 #endif
204 
205 /* put around conditional expressions if you are very sure that the  */
206 /* expression is mostly true or mostly false. note that these return */
207 /* booleans, not the expression.                                     */
208 #define ecb_expect_false(expr) ecb_expect (!!(expr), 0)
209 #define ecb_expect_true(expr)  ecb_expect (!!(expr), 1)
210 /* for compatibility to the rest of the world */
211 #define ecb_likely(expr)   ecb_expect_true  (expr)
212 #define ecb_unlikely(expr) ecb_expect_false (expr)
213 
214 /* count trailing zero bits and count # of one bits */
215 #if ECB_GCC_VERSION(3,4)
216   /* we assume int == 32 bit, long == 32 or 64 bit and long long == 64 bit */
217   #define ecb_ld32(x)      (__builtin_clz      (x) ^ 31)
218   #define ecb_ld64(x)      (__builtin_clzll    (x) ^ 63)
219   #define ecb_ctz32(x)      __builtin_ctz      (x)
220   #define ecb_ctz64(x)      __builtin_ctzll    (x)
221   #define ecb_popcount32(x) __builtin_popcount (x)
222   /* no popcountll */
223 #else
224   ecb_function_ int ecb_ctz32 (uint32_t x) ecb_const;
225   ecb_function_ int
ecb_ctz32(uint32_t x)226   ecb_ctz32 (uint32_t x)
227   {
228     int r = 0;
229 
230     x &= ~x + 1; /* this isolates the lowest bit */
231 
232 #if ECB_branchless_on_i386
233     r += !!(x & 0xaaaaaaaa) << 0;
234     r += !!(x & 0xcccccccc) << 1;
235     r += !!(x & 0xf0f0f0f0) << 2;
236     r += !!(x & 0xff00ff00) << 3;
237     r += !!(x & 0xffff0000) << 4;
238 #else
239     if (x & 0xaaaaaaaa) r +=  1;
240     if (x & 0xcccccccc) r +=  2;
241     if (x & 0xf0f0f0f0) r +=  4;
242     if (x & 0xff00ff00) r +=  8;
243     if (x & 0xffff0000) r += 16;
244 #endif
245 
246     return r;
247   }
248 
249   ecb_function_ int ecb_ctz64 (uint64_t x) ecb_const;
250   ecb_function_ int
ecb_ctz64(uint64_t x)251   ecb_ctz64 (uint64_t x)
252   {
253     int shift = x & 0xffffffffU ? 0 : 32;
254     return ecb_ctz32 (x >> shift) + shift;
255   }
256 
257   ecb_function_ int ecb_popcount32 (uint32_t x) ecb_const;
258   ecb_function_ int
ecb_popcount32(uint32_t x)259   ecb_popcount32 (uint32_t x)
260   {
261     x -=  (x >> 1) & 0x55555555;
262     x  = ((x >> 2) & 0x33333333) + (x & 0x33333333);
263     x  = ((x >> 4) + x) & 0x0f0f0f0f;
264     x *= 0x01010101;
265 
266     return x >> 24;
267   }
268 
269   ecb_function_ int ecb_ld32 (uint32_t x) ecb_const;
ecb_ld32(uint32_t x)270   ecb_function_ int ecb_ld32 (uint32_t x)
271   {
272     int r = 0;
273 
274     if (x >> 16) { x >>= 16; r += 16; }
275     if (x >>  8) { x >>=  8; r +=  8; }
276     if (x >>  4) { x >>=  4; r +=  4; }
277     if (x >>  2) { x >>=  2; r +=  2; }
278     if (x >>  1) {           r +=  1; }
279 
280     return r;
281   }
282 
283   ecb_function_ int ecb_ld64 (uint64_t x) ecb_const;
ecb_ld64(uint64_t x)284   ecb_function_ int ecb_ld64 (uint64_t x)
285   {
286     int r = 0;
287 
288     if (x >> 32) { x >>= 32; r += 32; }
289 
290     return r + ecb_ld32 (x);
291   }
292 #endif
293 
294 /* popcount64 is only available on 64 bit cpus as gcc builtin */
295 /* so for this version we are lazy */
296 ecb_function_ int ecb_popcount64 (uint64_t x) ecb_const;
297 ecb_function_ int
ecb_popcount64(uint64_t x)298 ecb_popcount64 (uint64_t x)
299 {
300   return ecb_popcount32 (x) + ecb_popcount32 (x >> 32);
301 }
302 
303 ecb_inline uint8_t  ecb_rotl8  (uint8_t  x, unsigned int count) ecb_const;
304 ecb_inline uint8_t  ecb_rotr8  (uint8_t  x, unsigned int count) ecb_const;
305 ecb_inline uint16_t ecb_rotl16 (uint16_t x, unsigned int count) ecb_const;
306 ecb_inline uint16_t ecb_rotr16 (uint16_t x, unsigned int count) ecb_const;
307 ecb_inline uint32_t ecb_rotl32 (uint32_t x, unsigned int count) ecb_const;
308 ecb_inline uint32_t ecb_rotr32 (uint32_t x, unsigned int count) ecb_const;
309 ecb_inline uint64_t ecb_rotl64 (uint64_t x, unsigned int count) ecb_const;
310 ecb_inline uint64_t ecb_rotr64 (uint64_t x, unsigned int count) ecb_const;
311 
ecb_rotl8(uint8_t x,unsigned int count)312 ecb_inline uint8_t  ecb_rotl8  (uint8_t  x, unsigned int count) { return (x >> ( 8 - count)) | (x << count); }
ecb_rotr8(uint8_t x,unsigned int count)313 ecb_inline uint8_t  ecb_rotr8  (uint8_t  x, unsigned int count) { return (x << ( 8 - count)) | (x >> count); }
ecb_rotl16(uint16_t x,unsigned int count)314 ecb_inline uint16_t ecb_rotl16 (uint16_t x, unsigned int count) { return (x >> (16 - count)) | (x << count); }
ecb_rotr16(uint16_t x,unsigned int count)315 ecb_inline uint16_t ecb_rotr16 (uint16_t x, unsigned int count) { return (x << (16 - count)) | (x >> count); }
ecb_rotl32(uint32_t x,unsigned int count)316 ecb_inline uint32_t ecb_rotl32 (uint32_t x, unsigned int count) { return (x >> (32 - count)) | (x << count); }
ecb_rotr32(uint32_t x,unsigned int count)317 ecb_inline uint32_t ecb_rotr32 (uint32_t x, unsigned int count) { return (x << (32 - count)) | (x >> count); }
ecb_rotl64(uint64_t x,unsigned int count)318 ecb_inline uint64_t ecb_rotl64 (uint64_t x, unsigned int count) { return (x >> (64 - count)) | (x << count); }
ecb_rotr64(uint64_t x,unsigned int count)319 ecb_inline uint64_t ecb_rotr64 (uint64_t x, unsigned int count) { return (x << (64 - count)) | (x >> count); }
320 
321 #if ECB_GCC_VERSION(4,3)
322   #define ecb_bswap16(x) (__builtin_bswap32 (x) >> 16)
323   #define ecb_bswap32(x)  __builtin_bswap32 (x)
324   #define ecb_bswap64(x)  __builtin_bswap64 (x)
325 #else
326   ecb_function_ uint16_t ecb_bswap16 (uint16_t x) ecb_const;
327   ecb_function_ uint16_t
ecb_bswap16(uint16_t x)328   ecb_bswap16 (uint16_t x)
329   {
330     return ecb_rotl16 (x, 8);
331   }
332 
333   ecb_function_ uint32_t ecb_bswap32 (uint32_t x) ecb_const;
334   ecb_function_ uint32_t
ecb_bswap32(uint32_t x)335   ecb_bswap32 (uint32_t x)
336   {
337     return (((uint32_t)ecb_bswap16 (x)) << 16) | ecb_bswap16 (x >> 16);
338   }
339 
340   ecb_function_ uint64_t ecb_bswap64 (uint64_t x) ecb_const;
341   ecb_function_ uint64_t
ecb_bswap64(uint64_t x)342   ecb_bswap64 (uint64_t x)
343   {
344     return (((uint64_t)ecb_bswap32 (x)) << 32) | ecb_bswap32 (x >> 32);
345   }
346 #endif
347 
348 #if ECB_GCC_VERSION(4,5)
349   #define ecb_unreachable() __builtin_unreachable ()
350 #else
351   /* this seems to work fine, but gcc always emits a warning for it :/ */
352   ecb_function_ void ecb_unreachable (void) ecb_noreturn;
ecb_unreachable(void)353   ecb_function_ void ecb_unreachable (void) { }
354 #endif
355 
356 /* try to tell the compiler that some condition is definitely true */
357 #define ecb_assume(cond) do { if (!(cond)) ecb_unreachable (); } while (0)
358 
359 ecb_function_ unsigned char ecb_byteorder_helper (void) ecb_const;
360 ecb_function_ unsigned char
ecb_byteorder_helper(void)361 ecb_byteorder_helper (void)
362 {
363   const uint32_t u = 0x11223344;
364   return *(unsigned char *)&u;
365 }
366 
367 ecb_function_ ecb_bool ecb_big_endian    (void) ecb_const;
ecb_big_endian(void)368 ecb_function_ ecb_bool ecb_big_endian    (void) { return ecb_byteorder_helper () == 0x11; }
369 ecb_function_ ecb_bool ecb_little_endian (void) ecb_const;
ecb_little_endian(void)370 ecb_function_ ecb_bool ecb_little_endian (void) { return ecb_byteorder_helper () == 0x44; }
371 
372 #if ECB_GCC_VERSION(3,0) || ECB_C99
373   #define ecb_mod(m,n) ((m) % (n) + ((m) % (n) < 0 ? (n) : 0))
374 #else
375   #define ecb_mod(m,n) ((m) < 0 ? ((n) - 1 - ((-1 - (m)) % (n))) : ((m) % (n)))
376 #endif
377 
378 #if __cplusplus
379   template<typename T>
ecb_div_rd(T val,T div)380   static inline T ecb_div_rd (T val, T div)
381   {
382     return val < 0 ? - ((-val + div - 1) / div) : (val          ) / div;
383   }
384   template<typename T>
ecb_div_ru(T val,T div)385   static inline T ecb_div_ru (T val, T div)
386   {
387     return val < 0 ? - ((-val          ) / div) : (val + div - 1) / div;
388   }
389 #else
390   #define ecb_div_rd(val,div) ((val) < 0 ? - ((-(val) + (div) - 1) / (div)) : ((val)            ) / (div))
391   #define ecb_div_ru(val,div) ((val) < 0 ? - ((-(val)            ) / (div)) : ((val) + (div) - 1) / (div))
392 #endif
393 
394 #if ecb_cplusplus_does_not_suck
395   /* does not work for local types (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm) */
396   template<typename T, int N>
ecb_array_length(const T (& arr)[N])397   static inline int ecb_array_length (const T (&arr)[N])
398   {
399     return N;
400   }
401 #else
402   #define ecb_array_length(name) (sizeof (name) / sizeof (name [0]))
403 #endif
404 
405 #endif
406 
407