alignment on stack-allocated arrays/structs

Robert Jacques sandford at jhu.edu
Tue Nov 17 13:56:16 PST 2009


On Tue, 17 Nov 2009 15:12:50 -0500, Trass3r <mrmocool at gmx.de> wrote:

> I originally posted a question about this in D.learn. bearophile advised  
> me to ask for that feature here.
>
>
> Original post:
> ==============
>
> OpenCL requires all types to be naturally aligned.
>
> The D specs state:
> "AlignAttribute is ignored when applied to declarations that are not  
> struct members."
>
> Could there arise any problems translating the following
>
> /*
>   * Vector types
>   *
>   *  Note:   OpenCL requires that all types be naturally aligned.
>   *          This means that vector types must be naturally aligned.
>   *          For example, a vector of four floats must be aligned to
>   *          a 16 byte boundary (calculated as 4 * the natural 4-byte
>   *          alignment of the float).  The alignment qualifiers here
>   *          will only function properly if your compiler supports them
>   *          and if you don't actively work to defeat them.  For example,
>   *          in order for a cl_float4 to be 16 byte aligned in a struct,
>   *          the start of the struct must itself be 16-byte aligned.
>   *
>   *          Maintaining proper alignment is the user's responsibility.
>   */
>
> typedef double          cl_double2[2]   __attribute__((aligned(16)));
> typedef double          cl_double4[4]   __attribute__((aligned(32)));
> typedef double          cl_double8[8]   __attribute__((aligned(64)));
> typedef double          cl_double16[16] __attribute__((aligned(128)));
>
>
>
> into just
>
>
> alias double[2]    cl_double2;
> alias double[4]    cl_double4;
> alias double[8]    cl_double8;
> alias double[16]   cl_double16;
>
> ?

To the best of my knowlegde, D only supports align(1) and align(4). On the  
other hand, compile time introspection allows my CUDA api to convert  
alignment correctly for any given struct.

As for your question, yes, there's lot's of trouble using simple aliases.  
You'll run into alignment issues with both function calling and if you use  
cl_double2, etc in structs. Of course, alignment issues only raise their  
ugly heads some of the time, which often leads to brittle code. A robust  
OpenCL binding for D needs to do alignment correction.



More information about the Digitalmars-d mailing list