| 1 | module Simd; |
| 2 | (* Code procedures with SSE2 and the bit scans: a search sixteen bytes |
| 3 | at a time, and the counts of bits *) |
| 4 | import Out; |
| 5 | import SYSTEM; |
| 6 | |
| 7 | (* the first place of b in s, or -1: its address in rdi, its length in rsi, b in dl *) |
| 8 | proc index(s: []U8; b: U8): INT; |
| 9 | code |
| 10 | movd xmm1, edx; |
| 11 | punpcklbw xmm1, xmm1; (* b in the low two bytes... *) |
| 12 | punpcklwd xmm1, xmm1; (* ...in the low four... *) |
| 13 | pshufd xmm1, xmm1, 0; (* ...and in all sixteen *) |
| 14 | xor ecx, ecx; |
| 15 | blocks: |
| 16 | lea rax, [rcx + 16]; |
| 17 | cmp rax, rsi; |
| 18 | ja tail; |
| 19 | movdqu xmm0, [rdi + rcx]; |
| 20 | pcmpeqb xmm0, xmm1; |
| 21 | pmovmskb eax, xmm0; |
| 22 | test eax, eax; |
| 23 | jnz found; |
| 24 | add rcx, 16; |
| 25 | jmp blocks; |
| 26 | found: |
| 27 | bsf eax, eax; |
| 28 | add rax, rcx; |
| 29 | ret; |
| 30 | tail: |
| 31 | cmp rcx, rsi; |
| 32 | jae missing; |
| 33 | cmp [rdi + rcx], dl; |
| 34 | je here; |
| 35 | inc rcx; |
| 36 | jmp tail; |
| 37 | here: |
| 38 | mov rax, rcx; |
| 39 | ret; |
| 40 | missing: |
| 41 | mov rax, -1; |
| 42 | ret; |
| 43 | end index; |
| 44 | |
| 45 | (* the bits set in x, the places of its lowest and highest, and its |
| 46 | leading zeros, packed as count + 100 * (low + 100 * (high + 100 * lead)) *) |
| 47 | proc bits(x: U64): I64; |
| 48 | code |
| 49 | popcnt rax, rdi; |
| 50 | tzcnt rcx, rdi; |
| 51 | imul rcx, rcx, 100; |
| 52 | add rax, rcx; |
| 53 | bsr rcx, rdi; |
| 54 | imul rcx, rcx, 10000; |
| 55 | add rax, rcx; |
| 56 | lzcnt rcx, rdi; |
| 57 | imul rcx, rcx, 1000000; |
| 58 | add rax, rcx; |
| 59 | ret; |
| 60 | end bits; |
| 61 | |
| 62 | proc main*; |
| 63 | var buf: [40]U8; i: INT; |
| 64 | begin |
| 65 | for i := 0 to 39 do buf[i] := 'a'; end; |
| 66 | buf[37] := 'x'; buf[20] := 'y'; buf[5] := 'z'; |
| 67 | Out.int(index(buf[0..40], 'z')); Out.str(" "); |
| 68 | Out.int(index(buf[0..40], 'y')); Out.str(" "); |
| 69 | Out.int(index(buf[0..40], 'x')); Out.str(" "); |
| 70 | Out.int(index(buf[0..40], 'q')); Out.str(" "); |
| 71 | Out.int(index(buf[0..0], 'a')); Out.str(" "); |
| 72 | Out.int(index(buf[6..21], 'y')); Out.ln; |
| 73 | Out.int(bits(0B0A0H)); Out.ln; |
| 74 | end; |
| 75 | |
| 76 | end Simd. |