summaryrefslogtreecommitdiffstats
path: root/source/base/base_simd.cpp
blob: 61791d2b85d121ad559b9b457f3291f6355a35d4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//- simd / bit helpers, one api on both architectures
// NOTE: x86-64: sse2 (baseline on every x86-64 cpu), arm64: neon (baseline on every aarch64 cpu).
// nothing here needs avx or sve, so release builds stay portable without -march flags.

#if ARCH_ARM
#include <arm_neon.h>
#elif ARCH_X86 || ARCH_x86_64
#include <emmintrin.h>
#endif
#if COMPILER_MSVC
#include <intrin.h>
#endif

internal u32 simd_ctz32(u32 x)
{
#if COMPILER_MSVC
	unsigned long index;
	_BitScanForward(&index, x);
	return (u32)index;
#else
	return (u32)__builtin_ctz(x);
#endif
}

internal u32 simd_ctz64(u64 x)
{
#if COMPILER_MSVC
	unsigned long index;
	_BitScanForward64(&index, x);
	return (u32)index;
#else
	return (u32)__builtin_ctzll(x);
#endif
}

// NOTE: index of the first `byte` in data, or size when there is none
internal u64 simd_find_byte(u8 *data, u64 size, u8 byte)
{
	u64 index = 0;
#if ARCH_ARM
	uint8x16_t needle = vdupq_n_u8(byte);
	for(; index + 16 <= size; index += 16) {
		uint8x16_t eq = vceqq_u8(vld1q_u8(data + index), needle);
		// NOTE: neon has no movemask. shift-narrow each 16 bit lane by 4 -> one nibble per byte
		uint8x8_t narrowed = vshrn_n_u16(vreinterpretq_u16_u8(eq), 4);
		u64       mask     = vget_lane_u64(vreinterpret_u64_u8(narrowed), 0);
		if(mask) return index + (simd_ctz64(mask) >> 2);
	}
#elif ARCH_X86 || ARCH_x86_64
	__m128i needle = _mm_set1_epi8((char)byte);
	for(; index + 16 <= size; index += 16) {
		__m128i chunk = _mm_loadu_si128((const __m128i *)(data + index));
		u32     mask  = (u32)_mm_movemask_epi8(_mm_cmpeq_epi8(chunk, needle));
		if(mask) return index + simd_ctz32(mask);
	}
#endif
	for(; index < size; ++index) {
		if(data[index] == byte) return index;
	}
	return size;
}

// NOTE: count of `byte` in data (newlines in a buffer, say)
internal u64 simd_count_byte(u8 *data, u64 size, u8 byte)
{
	u64 count = 0, index = 0;
#if ARCH_ARM
	uint8x16_t needle = vdupq_n_u8(byte);
	for(; index + 16 <= size; index += 16) {
		uint8x16_t eq = vceqq_u8(vld1q_u8(data + index), needle);
		count += vaddvq_u8(vshrq_n_u8(eq, 7));
	}
#elif ARCH_X86 || ARCH_x86_64
	__m128i needle = _mm_set1_epi8((char)byte);
	for(; index + 16 <= size; index += 16) {
		__m128i chunk = _mm_loadu_si128((const __m128i *)(data + index));
		u32     mask  = (u32)_mm_movemask_epi8(_mm_cmpeq_epi8(chunk, needle));
#if COMPILER_MSVC
		count += __popcnt(mask);
#else
		count += (u64)__builtin_popcount(mask);
#endif
	}
#endif
	for(; index < size; ++index) count += (data[index] == byte);
	return count;
}