feature. See also
. The project being documented here (as the example) is the Zig library itself.
simd.suggestVectorLengthForCpu
pub fn suggestVectorLengthForCpu(comptime T: type, comptime cpu: std.Target.Cpu) ?comptime_int
File
Code
pub fn suggestVectorLengthForCpu(comptime T: type, comptime cpu: std.Target.Cpu) ?comptime_int {
@setEvalBranchQuota(2_000);
const element_bit_size = @max(8, std.math.ceilPowerOfTwo(u16, @bitSizeOf(T)) catch unreachable);
const vector_bit_size: u16 = blk: {
if (cpu.arch.isX86()) {
if (T == bool and cpu.has(.x86, .prefer_mask_registers)) return 64;
if (builtin.zig_backend != .stage2_x86_64 and cpu.has(.x86, .avx512f) and !cpu.hasAny(.x86, &.{ .prefer_256_bit, .prefer_128_bit })) break :blk 512;
if (cpu.hasAny(.x86, &.{ .prefer_256_bit, .avx2 }) and !cpu.has(.x86, .prefer_128_bit)) break :blk 256;
if (cpu.has(.x86, .sse)) break :blk 128;
if (cpu.hasAny(.x86, &.{ .mmx, .@"3dnow" })) break :blk 64;
} else if (cpu.arch.isArm()) {
if (cpu.has(.arm, .neon)) break :blk 128;
} else if (cpu.arch.isAARCH64()) {
// AWS Graviton3 supports 256-bit SVE
// Fujitsu A64FX supports 512-bit SVE
// -> 256-bit seems like a good default for now.
if (cpu.has(.aarch64, .sve)) break :blk 256;
if (cpu.has(.aarch64, .neon)) break :blk 128;
} else if (cpu.arch == .hexagon) {
if (cpu.has(.hexagon, .hvx_length64b)) break :blk 512;
if (cpu.has(.hexagon, .hvx)) break :blk 1024;
} else if (cpu.arch.isLoongArch()) {
if (cpu.has(.loongarch, .lasx)) break :blk 256;
if (cpu.has(.loongarch, .lsx)) break :blk 128;
} else if (cpu.arch.isMIPS()) {
if (cpu.has(.mips, .msa)) break :blk 128;
if (cpu.has(.mips, .mips3d)) break :blk 64;
} else if (cpu.arch.isPowerPC()) {
if (cpu.has(.powerpc, .vsx)) break :blk 128;
if (cpu.has(.powerpc, .altivec)) break :blk 128;
} else if (cpu.arch.isRISCV()) {
// The usual vector length in most RISC-V cpus is 256 bits, however it can get to multiple kB.
if (cpu.has(.riscv, .v)) {
inline for (.{
.{ .zvl65536b, 65536 },
.{ .zvl32768b, 32768 },
.{ .zvl16384b, 16384 },
.{ .zvl8192b, 8192 },
.{ .zvl4096b, 4096 },
.{ .zvl2048b, 2048 },
.{ .zvl1024b, 1024 },
.{ .zvl512b, 512 },
.{ .zvl256b, 256 },
.{ .zvl128b, 128 },
.{ .zvl64b, 64 },
.{ .zvl32b, 32 },
}) |mapping| {
if (cpu.has(.riscv, mapping[0])) break :blk mapping[1];
}
break :blk 256;
}
} else if (cpu.arch == .s390x) {
if (cpu.has(.s390x, .vector)) break :blk 128;
} else if (cpu.arch.isSPARC()) {
if (cpu.hasAny(.sparc, &.{ .vis, .vis2, .vis3 })) break :blk 64;
} else if (cpu.arch == .kvx) {
break :blk 1024;
} else if (cpu.arch == .ve) {
if (cpu.has(.ve, .vpu)) break :blk 2048;
} else if (cpu.arch.isWasm()) {
if (cpu.has(.wasm, .simd128)) break :blk 128;
}
return null;
};
if (vector_bit_size <= element_bit_size) return null;
return @divExact(vector_bit_size, element_bit_size);
}