Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn on -mavx2 for only particular part of source code?

Could I force compiler to compile some intrinsic functions outside -march setting in some particular part of code?

Of course, the rest would remain within -march setting.

Is it possible to enable -mavx2 on only specific part of source code?

Or is the only way that I must compile -mavx2 section separately?

like image 673
sandthorn Avatar asked Sep 01 '25 11:09

sandthorn


1 Answers

Try __attribute__((target("avx2"))). Both GCC and Clang support it.

Example:

#include <stdlib.h>
#include <stdio.h>
#include <immintrin.h>

__attribute__((target("avx2")))
int add_with_avx2(int a, int b) {
    __m256i av = _mm256_set_epi32(a, 0, 0, 0, 0, 0, 0, 0);
    __m256i bv = _mm256_set_epi32(b, 0, 0, 0, 0, 0, 0, 0);
    __m256i result = _mm256_add_epi32(av, bv);
    return ((int*)&result)[7];
}

int main(void) {
    return add_with_avx2(5, 6);
}

However, it's probably a better idea to put the functions that need intrinsics in a seperate file, in case you ever need to use a compiler that doesn't have this feature.

like image 166
Functino Avatar answered Sep 04 '25 01:09

Functino