Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache-aligned stack variables

Using new C++11 alignment tools I wanted to make sure that a set of temporary (stack) variables will lie in one cache line. My first naive attempt was as follows:

int main() {
    alignas(64) int a; // 0x7fffc58aac80, properly aligned at 64
    int b; // 0x7fffc58aac7c
    int c; // 0x7fffc58aac78
    return 0;
}

Stupid me! Stack doesn't allocate the variables this way, thus a will be on different cache line than b and c.

Does this mean that the only way to properly align several variables is through an aggregate?

struct alignas(64) Abc {
   int x;
   int y;
   int z;
};

int main() {
   Abc foo;
   // x 0x7fff40c2d3c0 (aligned at 64)
   // y 0x7fff40c2d3c4
   // z 0x7fff40c2d3c8   
   return 0;
}

Compiler: Clang 3.2

like image 854
Red XIII Avatar asked Mar 24 '13 00:03

Red XIII


1 Answers

To properly align several variables you must use an aggregate, because the layout for automatic variables is not defined. I can't find anything in the C++11 standard that says variables with automatic storage have to be allocated on the stack in the same order they are defined. Section 5.9 of the standard insists that only a few kinds of pointer comparisons are defined, and comparisons between variables with automatic storage is not among those listed as defined.

like image 141
razeh Avatar answered Sep 30 '22 02:09

razeh