How to check if Target supports various instructions, avx512f

Do you know how I can check if the build Target supports various instructions e.g. avx2, avx512, sse3 etc. So far I have this, but it doesn’t work:

const has_avx512f = std.Target.Cpu.Feature.Set.isEnabled(features, @intFromEnum(std.Target.x86.Feature.avx512f));

>>>  zig build --verbose
/Users/sbi8kc2/.zvm/master/lib/std/fmt.zig:470:5: error: invalid format string 's' for type 'comptime_int'
    @compileError("invalid format string '" ++ fmt ++ "' for type '" ++ @typeName(@TypeOf(value)) ++ "'");

Thanks for any help!

You can access the current cpu from builtin.cpu

const builtin = @import("builtin");
const cpu: std.Target.Cpu = builtin.cpu;
_ = cpu.features;

cpu.features is a list with all the features.

Use zig build-exe --show-builtin or zig build-exe --show-builtin -target aarch64-linux-musl to view all the builtin declarations with values for the current target.

1 Like

Thanks @dimdin. I’m still a bit confused how to use this list, do I need to use the isEnabled function, how do I work out what index is needed?

const builtin = @import("builtin");
const std = @import("std");

pub fn main() void {
    const has_avx512f = std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f);
    std.debug.print("{}\n", .{avx512f});
}

Note that builtin.cpu is the host cpu and that you must assert that the cpu arch is x86, in order to avoid getting the wrong value.

1 Like

Thanks @mperillo. I run into the same error with that code. Im using zig 0.12.0-dev.2618+39ec3d311, perhaps that is an issue?

zig build --verbose
/Users/sbi8kc2/.zvm/master/lib/std/fmt.zig:470:5: error: invalid format string 's' for type 'comptime_int'
    @compileError("invalid format string '" ++ fmt ++ "' for type '" ++ @typeName(@TypeOf(value)) ++ "'");

This also gives the same error:

_ = builtin.cpu.features.isEnabled(@intFromEnum(std.Target.x86.Feature.avx512f));

Try running zig build --verbose -freference-trace in order to find the original culprit.

Running the code with zig run works correctly, printing true.

1 Like

There was a typo avx512f instead of has_avx512f.

const builtin = @import("builtin");
const std = @import("std");

pub fn main() void {
    const has_avx512f = std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f);
    std.debug.print("{}\n", .{has_avx512f});
}

Source of featureSetHas is:

pub fn featureSetHas(set: Set, feature: F) bool {
    return set.isEnabled(@intFromEnum(feature));
}

These are equivalent:

const has_avx512f = std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f);
const has_avx512f = builtin.cpu.features.isEnabled(@intFromEnum(std.Target.x86.Feature.avx512f));
2 Likes