Question

If in a function I need a fixed shuffle mask, should I set it as const or static const?

const __m128i SHUFFLE_MASK = _mm_setr_epi8(0,  4,  8, 12, -1, -1, -1, -1,
                                           -1, -1, -1, -1, -1, -1, -1, -1);

static const __m128i SHUFFLE_MASK = _mm_setr_epi8(0,  4,  8, 12, -1, -1, -1, -1,
                                                  -1, -1, -1, -1, -1, -1, -1, -1);
Was it helpful?

Solution

Usually _mm_setr_epi8 of compile-time-constant data ends up compiling to a 16B chunk of read-only data that gets loaded (or used as a memory operand). (look for labels like .LC0 in the gcc -S asm output). This is already optimal.

Emil Styrke commented that static const can end up including code to check if the static location is already initialized. Since there's no benefit, and a possible cost (at least on older gcc, haven't checked myself), avoid static const for vectors (esp. when the declaration and initializer is inside a function).

IDK if gcc ever optimizes a setr that has a pattern in the data into a movd and shuffle, or something like that. If so, then you might potentially want to avoid generating your constant with instructions, instead of having it there as a memory operand.

This seems like a very unlikely case, though. But if you need to defeat such an optimization, you can probably do it using a static (file-scope) char array to hold your constant, and casting a pointer to a vector type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top