Alex
Alex

Reputation: 1469

How to set the right alignment for an OpenCL array of structs?

I have the following structure:

C++:

struct ss{
    cl_float3 pos;
    cl_float value;
    cl_bool moved;
    cl_bool nextMoved;
    cl_int movePriority;
    cl_int nextMovePriority;
    cl_float value2;
    cl_float value3;
    cl_int neighbors[6];
    cl_float3 offsets[6];
    cl_float off1[6];
    cl_float off2[6];
};

OpenCL:

typedef struct{
    float3 nextPos;
    float value;
    bool moved;
    bool nextMoved;
    int movePriority;
    int nextMovePriority;
    float value2;
    float value3;
    int neighbors[6];
    float3 offsets[6];
    float off1[6];
    float off2[6];
} ss;

I have an array of these, and I pass them to an opencl Buffer, but when I operate with them in a kernel, the data gets corrupted.

I believe this is because of the alignment, I have read other posts about it

I need help understanding data alignment in OpenCL's buffers

Aligning for Memory Accesses in OpenCL/CUDA

But still, I don't fully get the idea of how to properly set the alignment to my struct. Also, I dont fully understand the attribute aligned and packed qualifiers.

So:

Q1. Could you show me how to align my struct to work properly?

Q2. Could you explain me or give me some link to understand all the alignment problem and the qualifiers?

Thanx.

Upvotes: 3

Views: 4226

Answers (1)

Dithermaster
Dithermaster

Reputation: 6333

I recommend declaring your structure from the widest types first down to the narrowest types. First, this avoids wasted unused spaces due to alignment. Second, this often avoids any headaches with different alignments on different devices.

So,

struct ss{
    cl_float3 pos;
    cl_float3 offsets[6];
    cl_float value;
    cl_float value2;
    cl_float value3;
    cl_float off1[6];
    cl_float off2[6];
    cl_int movePriority;
    cl_int nextMovePriority;
    cl_int neighbors[6];
    cl_bool moved;
    cl_bool nextMoved;
};

Also, beware of the float3 type; it is often a float4 on the GPU and if the host-side layout doesn't also do that, then your alignment will be off. You could switch to float4 to avoid this.

Upvotes: 4

Related Questions