I was searching on the web to find a proper solution, without much success. So I hope one of you know something about it: Is there any way to detect the "Intel Bit Manipulation Instruction Sets 2" (BMI2) compile time? I want to make some conditional thing based on the availability of it.
Asked
Active
Viewed 2,629 times
5
-
Presumably this means the CPU on which the compiler runs, not the CPU on which the compiled program will later run? – MSalters Aug 26 '15 at 10:14
-
yeah, this means the CPU on which the compiler runs (or more accurately the architecture which you compile for). the second option makes no sense: how would the compiler know which cpu will you later actually utilize to run your program? that scenario would need a dynamic runtime CPUID check, which would be simpler in this case. – plasmacel Aug 26 '15 at 14:42
2 Answers
7
With GCC you can check for the __BMI2__
macro. This macro will be defined if the target supports BMI2 (e.g. -mbmi2
,-march=haswell
). This is the macro that the instrinsic's headers (x86intrin.h
, bmi2intrin.h
) uses to check for BMI2 at compile time.
For runtime checks, __builtin_cpu_init()
and __builtin_cpu_supports("bmi2")
can be used in modern GCC (tested in GCC 5.1, 4.9 and lower doesn't have it).

RubenLaguna
- 21,435
- 13
- 113
- 151
1
Run the CPUID intrinsic function with EAX=7, ECX=0, then check bit 3 of the returned EBX register (the BMI1 flag). EBX bit 8 is the BMI2 flag. Consult your compiler's documentation for how to call CPUID and get the data back from it.

1201ProgramAlarm
- 32,384
- 7
- 42
- 56
-
3
-
-
You can't do it at compile time because the system it runs on is not the same as it is built on. If the systems are the same, you'll can know that ahead of time and can write your code knowing that the system it will run on will have the instructions, or that it will not, and enable that conditionally with a preprocessor define. – 1201ProgramAlarm Aug 27 '15 at 01:16