How to align stack at 32 byte boundary in GCC?

后端 未结 3 1835
轻奢々
轻奢々 2020-12-31 18:33

I\'m using MinGW64 build based on GCC 4.6.1 for Windows 64bit target. I\'m playing around with the new Intel\'s AVX instructions. My command line arguments are -march=

3条回答
  •  遥遥无期
    2020-12-31 18:52

    You can get the effect you want by

    1. Declaring your variables not as variables, but as fields in a struct
    2. Declaring an array that is larger than the structure by an appropriate amount of padding
    3. Doing pointer/address arithmetic to find a 32 byte aligned address in side the array
    4. Casting that address to a pointer to your struct
    5. Finally using the data members of your struct

    You can use the same technique when malloc() does not align stuff on the heap appropriately.

    E.g.

    void foo() {
        struct I_wish_these_were_32B_aligned {
              vec32B foo;
              char bar[32];
        }; // not - no variable definition, just the struct declaration.
        unsigned char a[sizeof(I_wish_these_were_32B_aligned) + 32)];
        unsigned char* a_aligned_to_32B = align_to_32B(a);
        I_wish_these_were_32B_aligned* s = (I_wish_these_were_32B_aligned)a_aligned_to_32B;
        s->foo = ...
    }
    

    where

    unsigned char* align_to_32B(unsiged char* a) {
         uint64_t u = (unit64_t)a;
         mask_aligned32B = (1 << 5) - 1;
         if (u & mask_aligned32B == 0) return (unsigned char*)u;
         return (unsigned char*)((u|mask_aligned_32B) + 1);
    }
    

提交回复
热议问题