#Proper way to pass cpu feature flags when compiling c++

1 messages · Page 1 of 1 (latest)

indigo barn
#

Hi, I am trying to compile tbb using the zig build system. Tbb's CMakeLists.txt passes the -mwaitpkg flag to the compiler to activate the relevant cpu flag.

I do the same in my build program by passing it as part of .flags when calling addCSourceFiles, like so

.flags = &.{
    "-std=c++11",
    "-fstack-protector-strong",
    "-ffp-model=precise",
    "-mrtm",
    "-mwaitpkg",
},

However, invoking zig build fails with error: always_inline function '_tpause' requires target feature 'waitpkg', but would be inlined into function 'prolonged_pause' that is compiled without support for 'waitpkg'

I can see the flag being passed along correctly:

error: the following command failed with 2 compilation errors:
/usr/bin/zig build-lib -cflags -std=c++11 -fstack-protector-strong -ffp-model=precise -mrtm -mwaitpkg -- ...

What does work is specifying the feature flag via -Dcpu, e.g. this command completes and generates libraries

zig build -Dcpu=x86_64_v2+waitpkg

Is passing -mxxx as part of the compiler flags incorrect, or what am I doing wrong?

indigo barn
#

Indeed it seems that passing -mxxx as a compiler flag is not the way to go. I have reduced the issue to this simple repro

test.cpp:

#include <x86intrin.h>

int main(int argc, char** argv) {
  _tpause(0, 1000);
  return 0;
}

compilation succeeds with

clang++ test.cpp -mwaitkpg

and

zig c++ test.cpp -mwaitpkg

but fails when compiled with

zig build-exe -cflags -mwaitpkg -- test.cpp -lc++

which is what the command line looks like when -mwaitpkg is provided in the .flags. So I am doing the wrong thing, but I haven't found what the correct thing to do is, yet

indigo barn
#

Gonna answer my own question, found out how via a mix of documentation and looking at the source code for zig.
This works

var target = b.standardTargetOptions(.{});
target.query.cpu_features_add.addFeature(@intFromEnum(std.Target.x86.Feature.waitpkg));

Not sure if there's a way to pass the wanted additional features directly in the target options, but if there is I couldn't figure out how