ref: 7192dd8d0b98e7ccddb00dea5be7e4e342e29025
parent: 78e765a33d9bb9c0662d205db1de7ecdf74aa867
author: Sigrid Solveig Haflínudóttir <ftrvxmtrx@gmail.com>
date: Wed Jan 13 13:33:55 EST 2021
add c_builtins*
--- a/README.md
+++ b/README.md
@@ -3,6 +3,7 @@
Random snippets of code that are in public domain.
Just copy and use for whatever you want.
+* `c_builtins*` a few __builtin_* for Plan 9, useful for porting other software
* `lrint.c` lrint* implementation
* `msr.c` MSR reading tool
* `nanosec.c` nanosec(), a replacement for (way more expensive) nsec()
--- /dev/null
+++ b/c_builtins.c
@@ -1,0 +1,29 @@
+int
+__builtin_ctz(unsigned int x)
+{
+ unsigned int r;
+ if(x == 0)
+ return 32;
+ for(r = 0; (x & 1) == 0; x >>= 1, r++);
+ return r;
+}
+
+int
+__builtin_clz(unsigned int x)
+{
+ unsigned int r;
+ if(x == 0)
+ return 32;
+ for(r = 0; (x & (1UL<<31)) == 0; x <<= 1, r++);
+ return r;
+}
+
+int
+__builtin_clzll(unsigned long long x)
+{
+ unsigned long long r;
+ if(x == 0)
+ return 64;
+ for(r = 0; (x & (1ULL<<63)) == 0; x <<= 1, r++);
+ return r;
+}
--- /dev/null
+++ b/c_builtins_amd64.s
@@ -1,0 +1,13 @@
+TEXT __builtin_ctz(SB),1,$0
+ BYTE $0x0F; BYTE $0xBC; BYTE $0xC5 /* BSFL RARG, AX */
+ RET
+
+TEXT __builtin_clz(SB),1,$0
+ BYTE $0x0F; BYTE $0xBD; BYTE $0xC5 /* BSRL RARG, AX */
+ XORL $31, AX
+ RET
+
+TEXT __builtin_clzll(SB),1,$0
+ BYTE $0x48; BYTE $0x0F; BYTE $0xBD; BYTE $0xC5 /* BSRQ RARG, AX */
+ XORL $63, AX
+ RET